<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<title>extension - RDoc Documentation</title>


<script src="./js/navigation.js" defer></script>
<script src="./js/search.js" defer></script>
<script src="./js/search_index.js" defer></script>
<script src="./js/searcher.js" defer></script>
<script src="./js/darkfish.js" defer></script>

<script src="./js/jquery-3.2.0.min.js"></script>

<script src="./js/vue.min.js"></script>
<script src="./js/js.cookie.min.js"></script>

<link href="./css/fonts.css" rel="stylesheet">
<link id='rdoccss' href="./css/rdoc.css" rel="stylesheet">
<link href="./css/carbon17.css" rel="stylesheet">

<script type="text/javascript">
  var rdoc_rel_prefix = "./";
  var index_rel_prefix = "./";
  var darkModeCsseHref = "./css/rdoc-dm.css"
  var defaultModeCssHref = "./css/rdoc.css"
  // var cssDarkmode = Cookies.get('darkmode');
  
  if( Cookies.get("darkmode") == "true") {
	$('#rdoccss').attr("href", darkModeCsseHref);
}

//  https://cssdeck.com/blog/simple-jquery-stylesheet-switcher/

document.write('<style type="text/css">body{display:none}</style>');

</script>


</head>
<body id="top" role="document" class="file">
  <!-- this is page.html -->
  <div id='actionbar' >
    <div class='wrapper mdiv'>
      <ul class='grids g0'></ul>
    </div> 
    <!-- VERSION HEADER for 3.3.0-preview2 NOT FOUND -->
  </div> <!-- end action bar -->


 <div class='wrapper hdiv'>

 


<nav id='vapp' role="navigation">
  <div id="project-navigation">
    <div id="home-section" role="region" title="Quick navigation" class="nav-section">
  <h2><a href="./index.html" rel="home">Home</a></h2>

  <div id="table-of-contents-navigation"  >
    <a href="./table_of_contents.html#pages">Pages</a>
    <a href="./table_of_contents.html#classes">Classes</a>
    <a href="./table_of_contents.html#methods">Methods</a>
  </div>
</div>

    <div id="search-section" role="search" class="project-section initially-hidden">
  <form action="#" method="get" accept-charset="utf-8">
    <div id="search-field-wrapper">
      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">
    </div>

    <ul id="search-results" aria-label="Search Results"
        aria-busy="false" aria-expanded="false"
        aria-atomic="false" class="initially-hidden"></ul>
  </form>
</div>

  </div>

  
<div class="nav-section">
  <h3>Table of Contents</h3>

  <ul class="link-list" role="directory">
    <li><a href="#label-Creating+extension+libraries+for+Ruby">Creating extension libraries for Ruby</a>
    <li><a href="#label-Basic+Knowledge">Basic Knowledge</a>
    <li><a href="#label-Ruby+data+types">Ruby data types</a>
    <li><a href="#label-Check+type+of+the+VALUE+data">Check type of the VALUE data</a>
    <li><a href="#label-Convert+VALUE+into+C+data">Convert VALUE into C data</a>
    <li><a href="#label-Convert+C+data+into+VALUE">Convert C data into VALUE</a>
    <li><a href="#label-Manipulating+Ruby+object">Manipulating Ruby object</a>
    <li><a href="#label-String+functions">String functions</a>
    <li><a href="#label-Array+functions">Array functions</a>
    <li><a href="#label-Extending+Ruby+with+C">Extending Ruby with C</a>
    <li><a href="#label-Adding+new+features+to+Ruby">Adding new features to Ruby</a>
    <li><a href="#label-Class+and+Module+Definition">Class and Module Definition</a>
    <li><a href="#label-Method+and+singleton+method+definition">Method and singleton method definition</a>
    <li><a href="#label-Constant+definition">Constant definition</a>
    <li><a href="#label-Use+Ruby+features+from+C">Use Ruby features from C</a>
    <li><a href="#label-Evaluate+Ruby+programs+in+a+string">Evaluate Ruby programs in a string</a>
    <li><a href="#label-ID+or+Symbol">ID or Symbol</a>
    <li><a href="#label-Invoke+Ruby+method+from+C">Invoke Ruby method from C</a>
    <li><a href="#label-Accessing+the+variables+and+constants">Accessing the variables and constants</a>
    <li><a href="#label-Information+sharing+between+Ruby+and+C">Information sharing between Ruby and C</a>
    <li><a href="#label-Ruby+constants+that+can+be+accessed+from+C">Ruby constants that can be accessed from C</a>
    <li><a href="#label-Global+variables+shared+between+C+and+Ruby">Global variables shared between C and Ruby</a>
    <li><a href="#label-Encapsulate+C+data+into+a+Ruby+object">Encapsulate C data into a Ruby object</a>
    <li><a href="#label-C+struct+to+Ruby+object">C struct to Ruby object</a>
    <li><a href="#label-Declaratively+marking-2Fcompacting+struct+references">Declaratively marking/compacting struct references</a>
    <li><a href="#label-Ruby+object+to+C+struct">Ruby object to C struct</a>
    <li><a href="#label-Example+-+Creating+the+dbm+Extension">Example - Creating the dbm Extension</a>
    <li><a href="#label-Make+the+directory">Make the directory</a>
    <li><a href="#label-Design+the+Library">Design the Library</a>
    <li><a href="#label-Write+the+C+Code">Write the C Code</a>
    <li><a href="#label-Prepare+extconf.rb">Prepare extconf.rb</a>
    <li><a href="#label-Prepare+depend+-28Optional-29">Prepare depend (Optional)</a>
    <li><a href="#label-Generate+Makefile">Generate Makefile</a>
    <li><a href="#label-Run+make">Run make</a>
    <li><a href="#label-Debug">Debug</a>
    <li><a href="#label-Done-21+Now+you+have+the+extension+library">Done! Now you have the extension library</a>
    <li><a href="#label-Appendix+A.+Ruby+header+and+source+files+overview">Appendix A. Ruby header and source files overview</a>
    <li><a href="#label-Ruby+header+files">Ruby header files</a>
    <li><a href="#label-Ruby+language+core">Ruby language core</a>
    <li><a href="#label-Ruby+syntax+parser">Ruby syntax parser</a>
    <li><a href="#label-Ruby+evaluator+-28a.k.a.+YARV-29">Ruby evaluator (a.k.a. YARV)</a>
    <li><a href="#label-Regular+expression+engine+-28Onigumo-29">Regular expression engine (Onigumo)</a>
    <li><a href="#label-Utility+functions">Utility functions</a>
    <li><a href="#label-Ruby+interpreter+implementation">Ruby interpreter implementation</a>
    <li><a href="#label-Class+library">Class library</a>
    <li><a href="#label-Multilingualization">Multilingualization</a>
    <li><a href="#label-goruby+interpreter+implementation">goruby interpreter implementation</a>
    <li><a href="#label-Appendix+B.+Ruby+extension+API+reference">Appendix B. Ruby extension API reference</a>
    <li><a href="#label-Types">Types</a>
    <li><a href="#label-Variables+and+constants">Variables and constants</a>
    <li><a href="#label-C+pointer+wrapping">C pointer wrapping</a>
    <li><a href="#label-Checking+VALUE+types">Checking VALUE types</a>
    <li><a href="#label-VALUE+type+conversion">VALUE type conversion</a>
    <li><a href="#label-Defining+classes+and+modules">Defining classes and modules</a>
    <li><a href="#label-Defining+global+variables">Defining global variables</a>
    <li><a href="#label-Constant+definition">Constant definition</a>
    <li><a href="#label-Method+definition">Method definition</a>
    <li><a href="#label-Invoking+Ruby+method">Invoking Ruby method</a>
    <li><a href="#label-Instance+variables">Instance variables</a>
    <li><a href="#label-Control+structure">Control structure</a>
    <li><a href="#label-Exceptions+and+errors">Exceptions and errors</a>
    <li><a href="#label-Threading">Threading</a>
    <li><a href="#label-Input-2FOutput+-28IO-29+on+a+single+file+descriptor">Input/Output (IO) on a single file descriptor</a>
    <li><a href="#label-I-2FO+multiplexing">I/O multiplexing</a>
    <li><a href="#label-Initialize+and+start+the+interpreter">Initialize and start the interpreter</a>
    <li><a href="#label-Hooks+for+the+interpreter+events">Hooks for the interpreter events</a>
    <li><a href="#label-Memory+usage">Memory usage</a>
    <li><a href="#label-Macros+for+compatibility">Macros for compatibility</a>
    <li><a href="#label-Defining+backward+compatible+macros+for+keyword+argument+functions">Defining backward compatible macros for keyword argument functions</a>
    <li><a href="#label-Appendix+C.+Functions+available+for+use+in+extconf.rb">Appendix C. Functions available for use in extconf.rb</a>
    <li><a href="#label-Appendix+D.+Generational+GC">Appendix D. Generational GC</a>
    <li><a href="#label-Incompatibility">Incompatibility</a>
    <li><a href="#label-Write+barriers">Write barriers</a>
    <li><a href="#label-Don-27t+touch+pointers+directly">Don’t touch pointers directly</a>
    <li><a href="#label-Consider+whether+to+insert+write+barriers">Consider whether to insert write barriers</a>
    <li><a href="#label-Combine+with+built-in+types">Combine with built-in types</a>
    <li><a href="#label-Insert+write+barriers">Insert write barriers</a>
    <li><a href="#label-Appendix+E.+RB_GC_GUARD+to+protect+from+premature+GC">Appendix E. RB_GC_GUARD to protect from premature GC</a>
    <li><a href="#label-Appendix+F.+Ractor+support">Appendix F. Ractor support</a>
  </ul>
</div>

  <button id='toggleThing' @click="toggleNav()" >Show/hide navigation</button>

  <div id="project-metadata">
   <div :class="isOpen ? 'block' : 'hidden' " id='toggleMe'>
    
<div id="fileindex-section" class="nav-section">
  <h3>Pages</h3>

  <ul class="link-list">
    <li><a href="./NEWS/NEWS-1_8_7.html">NEWS-1.8.7</a>
    <li><a href="./NEWS/NEWS-1_9_1.html">NEWS-1.9.1</a>
    <li><a href="./NEWS/NEWS-1_9_2.html">NEWS-1.9.2</a>
    <li><a href="./NEWS/NEWS-1_9_3.html">NEWS-1.9.3</a>
    <li><a href="./NEWS/NEWS-2_0_0.html">NEWS-2.0.0</a>
    <li><a href="./NEWS/NEWS-2_1_0.html">NEWS-2.1.0</a>
    <li><a href="./NEWS/NEWS-2_2_0.html">NEWS-2.2.0</a>
    <li><a href="./NEWS/NEWS-2_3_0.html">NEWS-2.3.0</a>
    <li><a href="./NEWS/NEWS-2_4_0.html">NEWS-2.4.0</a>
    <li><a href="./NEWS/NEWS-2_5_0.html">NEWS-2.5.0</a>
    <li><a href="./NEWS/NEWS-2_6_0.html">NEWS-2.6.0</a>
    <li><a href="./NEWS/NEWS-2_7_0.html">NEWS-2.7.0</a>
    <li><a href="./NEWS/NEWS-3_0_0_md.html">NEWS-3.0.0</a>
    <li><a href="./NEWS/NEWS-3_1_0_md.html">NEWS-3.1.0</a>
    <li><a href="./NEWS/NEWS-3_2_0_md.html">NEWS-3.2.0</a>
    <li><a href="./bsearch_rdoc.html">bsearch</a>
    <li><a href="./bug_triaging_rdoc.html">bug_triaging</a>
    <li><a href="./case_mapping_rdoc.html">case_mapping</a>
    <li><a href="./character_selectors_rdoc.html">character_selectors</a>
    <li><a href="./command_injection_rdoc.html">command_injection</a>
    <li><a href="./contributing_md.html">contributing</a>
    <li><a href="./contributing/building_ruby_md.html">building_ruby</a>
    <li><a href="./contributing/documentation_guide_md.html">documentation_guide</a>
    <li><a href="./contributing/glossary_md.html">glossary</a>
    <li><a href="./contributing/making_changes_to_ruby_md.html">making_changes_to_ruby</a>
    <li><a href="./contributing/making_changes_to_stdlibs_md.html">making_changes_to_stdlibs</a>
    <li><a href="./contributing/reporting_issues_md.html">reporting_issues</a>
    <li><a href="./contributing/testing_ruby_md.html">testing_ruby</a>
    <li><a href="./dig_methods_rdoc.html">dig_methods</a>
    <li><a href="./distribution_md.html">distribution</a>
    <li><a href="./dtrace_probes_rdoc.html">dtrace_probes</a>
    <li><a href="./encodings_rdoc.html">encodings</a>
    <li><a href="./extension_ja_rdoc.html">extension.ja</a>
    <li><a href="./extension_rdoc.html">extension</a>
    <li><a href="./fiber_md.html">fiber</a>
    <li><a href="./format_specifications_rdoc.html">format_specifications</a>
    <li><a href="./globals_rdoc.html">globals</a>
    <li><a href="./implicit_conversion_rdoc.html">implicit_conversion</a>
    <li><a href="./keywords_rdoc.html">keywords</a>
    <li><a href="./maintainers_md.html">maintainers</a>
    <li><a href="./marshal_rdoc.html">marshal</a>
    <li><a href="./memory_view_md.html">memory_view</a>
    <li><a href="./optparse/argument_converters_rdoc.html">argument_converters</a>
    <li><a href="./optparse/creates_option_rdoc.html">creates_option</a>
    <li><a href="./optparse/option_params_rdoc.html">option_params</a>
    <li><a href="./optparse/tutorial_rdoc.html">tutorial</a>
    <li><a href="./packed_data_rdoc.html">packed_data</a>
    <li><a href="./ractor_md.html">ractor</a>
    <li><a href="./regexp_rdoc.html">regexp</a>
    <li><a href="./regexp/methods_rdoc.html">methods</a>
    <li><a href="./regexp/unicode_properties_rdoc.html">unicode_properties</a>
    <li><a href="./ruby_3_3_0_preview2/COPYING.html">COPYING</a>
    <li><a href="./ruby_3_3_0_preview2/COPYING_ja.html">COPYING.ja</a>
    <li><a href="./ruby_3_3_0_preview2/LEGAL.html">LEGAL</a>
    <li><a href="./ruby_3_3_0_preview2/NEWS_md.html">NEWS</a>
    <li><a href="./ruby_3_3_0_preview2/README_ja_md.html">README.ja</a>
    <li><a href="./ruby_3_3_0_preview2/README_md.html">README</a>
    <li><a href="./security_rdoc.html">security</a>
    <li><a href="./signals_rdoc.html">signals</a>
    <li><a href="./standard_library_rdoc.html">standard_library</a>
    <li><a href="./strftime_formatting_rdoc.html">strftime_formatting</a>
    <li><a href="./syntax_rdoc.html">syntax</a>
    <li><a href="./syntax/assignment_rdoc.html">assignment</a>
    <li><a href="./syntax/calling_methods_rdoc.html">calling_methods</a>
    <li><a href="./syntax/comments_rdoc.html">comments</a>
    <li><a href="./syntax/control_expressions_rdoc.html">control_expressions</a>
    <li><a href="./syntax/exceptions_rdoc.html">exceptions</a>
    <li><a href="./syntax/literals_rdoc.html">literals</a>
    <li><a href="./syntax/methods_rdoc.html">methods</a>
    <li><a href="./syntax/miscellaneous_rdoc.html">miscellaneous</a>
    <li><a href="./syntax/modules_and_classes_rdoc.html">modules_and_classes</a>
    <li><a href="./syntax/pattern_matching_rdoc.html">pattern_matching</a>
    <li><a href="./syntax/precedence_rdoc.html">precedence</a>
    <li><a href="./syntax/refinements_rdoc.html">refinements</a>
    <li><a href="./timezones_rdoc.html">timezones</a>
    <li><a href="./windows_md.html">windows</a>
    <li><a href="./yjit/yjit_md.html">yjit</a>
    <li><a href="./yjit/yjit_hacking_md.html">yjit_hacking</a>
  </ul>
</div>

   </div>
  </div>
</nav>


<!--  carbon ads here -->

<div id='extraz'>
  <div class='adzbox-index'  >
   
  </div>
 </div>         


<main role="main" aria-label="Page extension.rdoc">

<h1 id="label-Creating+extension+libraries+for+Ruby">Creating extension libraries for Ruby<span><a href="#label-Creating+extension+libraries+for+Ruby">&para;</a> <a href="#top">&uarr;</a></span></h1>

<p>This document explains how to make extension libraries for Ruby.</p>

<h2 id="label-Basic+Knowledge">Basic Knowledge<span><a href="#label-Basic+Knowledge">&para;</a> <a href="#top">&uarr;</a></span></h2>

<p>In C, variables have types and data do not have types.  In contrast, Ruby variables do not have a static type, and data themselves have types, so data will need to be converted between the languages.</p>

<p>Objects in Ruby are represented by the C type ‘VALUE’.  Each VALUE data has its data type.</p>

<p>To retrieve C data from a VALUE, you need to:</p>
<ol><li>
<p>Identify the VALUE’s data type</p>
</li><li>
<p>Convert the VALUE into C data</p>
</li></ol>

<p>Converting to the wrong data type may cause serious problems.</p>

<h3 id="label-Ruby+data+types">Ruby data types<span><a href="#label-Ruby+data+types">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>The Ruby interpreter has the following data types:</p>
<dl class="rdoc-list note-list"><dt>T_NIL       
<dd>
<p>nil</p>
</dd><dt>T_OBJECT    
<dd>
<p>ordinary object</p>
</dd><dt>T_CLASS     
<dd>
<p>class</p>
</dd><dt>T_MODULE    
<dd>
<p>module</p>
</dd><dt>T_FLOAT     
<dd>
<p>floating point number</p>
</dd><dt>T_STRING    
<dd>
<p>string</p>
</dd><dt>T_REGEXP    
<dd>
<p>regular expression</p>
</dd><dt>T_ARRAY     
<dd>
<p>array</p>
</dd><dt>T_HASH      
<dd>
<p>associative array</p>
</dd><dt>T_STRUCT    
<dd>
<p>(Ruby) structure</p>
</dd><dt>T_BIGNUM    
<dd>
<p>multi precision integer</p>
</dd><dt>T_FIXNUM    
<dd>
<p>Fixnum(31bit or 63bit integer)</p>
</dd><dt>T_COMPLEX   
<dd>
<p>complex number</p>
</dd><dt>T_RATIONAL  
<dd>
<p>rational number</p>
</dd><dt>T_FILE      
<dd>
<p><a href="IO.html"><code>IO</code></a></p>
</dd><dt>T_TRUE      
<dd>
<p>true</p>
</dd><dt>T_FALSE     
<dd>
<p>false</p>
</dd><dt>T_DATA      
<dd>
<p>data</p>
</dd><dt>T_SYMBOL    
<dd>
<p>symbol</p>
</dd></dl>

<p>In addition, there are several other types used internally:</p>
<dl class="rdoc-list note-list"><dt>T_ICLASS    
<dd>
<p>included module</p>
</dd><dt>T_MATCH     
<dd>
<p><a href="MatchData.html"><code>MatchData</code></a> object</p>
</dd><dt>T_UNDEF     
<dd>
<p>undefined</p>
</dd><dt>T_NODE      
<dd>
<p>syntax tree node</p>
</dd><dt>T_ZOMBIE    
<dd>
<p>object awaiting finalization</p>
</dd></dl>

<p>Most of the types are represented by C structures.</p>

<h3 id="label-Check+type+of+the+VALUE+data">Check type of the VALUE data<span><a href="#label-Check+type+of+the+VALUE+data">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>The macro TYPE() defined in ruby.h shows the data type of the VALUE. TYPE() returns the constant number T_XXXX described above.  To handle data types, your code will look something like this:</p>

<pre>switch (TYPE(obj)) {
  case T_FIXNUM:
    /* process Fixnum */
    break;
  case T_STRING:
    /* process String */
    break;
  case T_ARRAY:
    /* process Array */
    break;
  default:
    /* raise exception */
    rb_raise(rb_eTypeError, &quot;not valid value&quot;);
    break;
}</pre>

<p>There is the data type check function</p>

<pre>void Check_Type(VALUE value, int type)</pre>

<p>which raises an exception if the VALUE does not have the type specified.</p>

<p>There are also faster check macros for fixnums and nil.</p>

<pre class="ruby"><span class="ruby-constant">FIXNUM_P</span>(<span class="ruby-identifier">obj</span>)
<span class="ruby-constant">NIL_P</span>(<span class="ruby-identifier">obj</span>)
</pre>

<h3 id="label-Convert+VALUE+into+C+data">Convert VALUE into C data<span><a href="#label-Convert+VALUE+into+C+data">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>The data for type T_NIL, T_FALSE, T_TRUE are nil, false, true respectively.  They are singletons for the data type. The equivalent C constants are: Qnil, Qfalse, Qtrue. RTEST() will return true if a VALUE is neither Qfalse nor Qnil. If you need to differentiate Qfalse from Qnil, specifically test against Qfalse.</p>

<p>The T_FIXNUM data is a 31bit or 63bit length fixed integer. This size depends on the size of long: if long is 32bit then T_FIXNUM is 31bit, if long is 64bit then T_FIXNUM is 63bit. T_FIXNUM can be converted to a C integer by using the FIX2INT() macro or FIX2LONG().  Though you have to check that the data is really FIXNUM before using them, they are faster.  FIX2LONG() never raises exceptions, but FIX2INT() raises <a href="RangeError.html"><code>RangeError</code></a> if the result is bigger or smaller than the size of int. There are also NUM2INT() and NUM2LONG() which converts any Ruby numbers into C integers.  These macros include a type check, so an exception will be raised if the conversion failed.  NUM2DBL() can be used to retrieve the double float value in the same way.</p>

<p>You can use the macros StringValue() and StringValuePtr() to get a char* from a VALUE. StringValue(var) replaces var’s value with the result of “var.to_str()”. StringValuePtr(var) does the same replacement and returns the char* representation of var.  These macros will skip the replacement if var is a <a href="String.html"><code>String</code></a>.  Notice that the macros take only the lvalue as their argument, to change the value of var in place.</p>

<p>You can also use the macro named StringValueCStr(). This is just like StringValuePtr(), but always adds a NUL character at the end of the result. If the result contains a NUL character, this macro causes the <a href="ArgumentError.html"><code>ArgumentError</code></a> exception. StringValuePtr() doesn’t guarantee the existence of a NUL at the end of the result, and the result may contain NUL.</p>

<p>Other data types have corresponding C structures, e.g. struct RArray for T_ARRAY etc. The VALUE of the type which has the corresponding structure can be cast to retrieve the pointer to the struct.  The casting macro will be of the form RXXXX for each data type; for instance, RARRAY(obj).  See “ruby.h”.  However, we do not recommend to access RXXXX data directly because these data structures are complex. Use corresponding rb_xxx() functions to access the internal struct. For example, to access an entry of array, use rb_ary_entry(ary, offset) and rb_ary_store(ary, offset, obj).</p>

<p>There are some accessing macros for structure members, for example ‘RSTRING_LEN(str)’ to get the size of the Ruby <a href="String.html"><code>String</code></a> object.  The allocated region can be accessed by ‘RSTRING_PTR(str)’.</p>

<p>Notice: Do not change the value of the structure directly, unless you are responsible for the result.  This ends up being the cause of interesting bugs.</p>

<h3 id="label-Convert+C+data+into+VALUE">Convert C data into VALUE<span><a href="#label-Convert+C+data+into+VALUE">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>To convert C data to Ruby values:</p>
<dl class="rdoc-list note-list"><dt>FIXNUM 
<dd>
<p>left shift 1 bit, and turn on its least significant bit (LSB).</p>
</dd><dt>Other pointer values 
<dd>
<p>cast to VALUE.</p>
</dd></dl>

<p>You can determine whether a VALUE is a pointer or not by checking its LSB.</p>

<p>Notice: Ruby does not allow arbitrary pointer values to be a VALUE.  They should be pointers to the structures which Ruby knows about.  The known structures are defined in &lt;ruby.h&gt;.</p>

<p>To convert C numbers to Ruby values, use these macros:</p>
<dl class="rdoc-list note-list"><dt>INT2FIX() 
<dd>
<p>for integers within 31bits.</p>
</dd><dt>INT2NUM() 
<dd>
<p>for arbitrary sized integers.</p>
</dd></dl>

<p>INT2NUM() converts an integer into a Bignum if it is out of the FIXNUM range, but is a bit slower.</p>

<h3 id="label-Manipulating+Ruby+object">Manipulating Ruby object<span><a href="#label-Manipulating+Ruby+object">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>As I already mentioned, it is not recommended to modify an object’s internal structure.  To manipulate objects, use the functions supplied by the Ruby interpreter. Some (not all) of the useful functions are listed below:</p>

<h4 id="label-String+functions"><a href="String.html"><code>String</code></a> functions<span><a href="#label-String+functions">&para;</a> <a href="#top">&uarr;</a></span></h4>
<dl class="rdoc-list note-list"><dt>rb_str_new(const char *ptr, long len) 
<dd>
<p>Creates a new Ruby string.</p>
</dd><dt>rb_str_new2(const char *ptr) 
<dt>rb_str_new_cstr(const char *ptr) 
<dd>
<p>Creates a new Ruby string from a C string.  This is equivalent to rb_str_new(ptr, strlen(ptr)).</p>
</dd><dt>rb_str_new_literal(const char *ptr) 
<dd>
<p>Creates a new Ruby string from a C string literal.</p>
</dd><dt>rb_sprintf(const char *format, …) 
<dt>rb_vsprintf(const char *format, va_list ap) 
<dd>
<p>Creates a new Ruby string with printf(3) format.</p>

<p>Note: In the format string, “%”PRIsVALUE can be used for <a href="Object.html#method-i-to_s"><code>Object#to_s</code></a> (or <a href="Object.html#method-i-inspect"><code>Object#inspect</code></a> if ‘+’ flag is set) output (and related argument must be a VALUE).  Since it conflicts with “%i”, for integers in format strings, use “%d”.</p>
</dd><dt>rb_str_append(VALUE str1, VALUE str2) 
<dd>
<p>Appends Ruby string str2 to Ruby string str1.</p>
</dd><dt>rb_str_cat(VALUE str, const char *ptr, long len) 
<dd>
<p>Appends len bytes of data from ptr to the Ruby string.</p>
</dd><dt>rb_str_cat2(VALUE str, const char* ptr) 
<dt>rb_str_cat_cstr(VALUE str, const char* ptr) 
<dd>
<p>Appends C string ptr to Ruby string str.  This function is equivalent to rb_str_cat(str, ptr, strlen(ptr)).</p>
</dd><dt>rb_str_catf(VALUE str, const char* format, …) 
<dt>rb_str_vcatf(VALUE str, const char* format, va_list ap) 
<dd>
<p>Appends C string format and successive arguments to Ruby string str according to a printf-like format.  These functions are equivalent to rb_str_append(str, rb_sprintf(format, …)) and rb_str_append(str, rb_vsprintf(format, ap)), respectively.</p>
</dd><dt>rb_enc_str_new(const char *ptr, long len, rb_encoding *enc) 
<dt>rb_enc_str_new_cstr(const char *ptr, rb_encoding *enc) 
<dd>
<p>Creates a new Ruby string with the specified encoding.</p>
</dd><dt>rb_enc_str_new_literal(const char *ptr, rb_encoding *enc) 
<dd>
<p>Creates a new Ruby string from a C string literal with the specified encoding.</p>
</dd><dt>rb_usascii_str_new(const char *ptr, long len) 
<dt>rb_usascii_str_new_cstr(const char *ptr) 
<dd>
<p>Creates a new Ruby string with encoding US-ASCII.</p>
</dd><dt>rb_usascii_str_new_literal(const char *ptr) 
<dd>
<p>Creates a new Ruby string from a C string literal with encoding US-ASCII.</p>
</dd><dt>rb_utf8_str_new(const char *ptr, long len) 
<dt>rb_utf8_str_new_cstr(const char *ptr) 
<dd>
<p>Creates a new Ruby string with encoding UTF-8.</p>
</dd><dt>rb_utf8_str_new_literal(const char *ptr) 
<dd>
<p>Creates a new Ruby string from a C string literal with encoding UTF-8.</p>
</dd><dt>rb_str_resize(VALUE str, long len) 
<dd>
<p>Resizes a Ruby string to len bytes.  If str is not modifiable, this function raises an exception.  The length of str must be set in advance.  If len is less than the old length the content beyond len bytes is discarded, else if len is greater than the old length the content beyond the old length bytes will not be preserved but will be garbage.  Note that RSTRING_PTR(str) may change by calling this function.</p>
</dd><dt>rb_str_set_len(VALUE str, long len) 
<dd>
<p>Sets the length of a Ruby string.  If str is not modifiable, this function raises an exception.  This function preserves the content up to len bytes, regardless RSTRING_LEN(str).  len must not exceed the capacity of str.</p>
</dd><dt>rb_str_modify(VALUE str) 
<dd>
<p>Prepares a Ruby string to modify.  If str is not modifiable, this function raises an exception, or if the buffer of str is shared, this function allocates new buffer to make it unshared.  Always you MUST call this function before modifying the contents using RSTRING_PTR and/or rb_str_set_len.</p>
</dd></dl>

<h4 id="label-Array+functions"><a href="Array.html"><code>Array</code></a> functions<span><a href="#label-Array+functions">&para;</a> <a href="#top">&uarr;</a></span></h4>
<dl class="rdoc-list note-list"><dt>rb_ary_new() 
<dd>
<p>Creates an array with no elements.</p>
</dd><dt>rb_ary_new2(long len) 
<dt>rb_ary_new_capa(long len) 
<dd>
<p>Creates an array with no elements, allocating internal buffer for len elements.</p>
</dd><dt>rb_ary_new3(long n, …) 
<dt>rb_ary_new_from_args(long n, …) 
<dd>
<p>Creates an n-element array from the arguments.</p>
</dd><dt>rb_ary_new4(long n, VALUE *elts) 
<dt>rb_ary_new_from_values(long n, VALUE *elts) 
<dd>
<p>Creates an n-element array from a C array.</p>
</dd><dt>rb_ary_to_ary(VALUE obj) 
<dd>
<p>Converts the object into an array. Equivalent to Object#to_ary.</p>
</dd></dl>

<p>There are many functions to operate an array.  They may dump core if other types are given.</p>
<dl class="rdoc-list note-list"><dt>rb_ary_aref(int argc, const VALUE *argv, VALUE ary) 
<dd>
<p>Equivalent to <a href="Array.html#method-i-5B-5D"><code>Array#[]</code></a>.</p>
</dd><dt>rb_ary_entry(VALUE ary, long offset) 
<dd>
<p>ary[offset]</p>
</dd><dt>rb_ary_store(VALUE ary, long offset, VALUE obj) 
<dd>
<p>ary[offset] = obj</p>
</dd><dt>rb_ary_subseq(VALUE ary, long beg, long len) 
<dd>
<p>ary[beg, len]</p>
</dd><dt>rb_ary_push(VALUE ary, VALUE val) 
<dt>rb_ary_pop(VALUE ary) 
<dt>rb_ary_shift(VALUE ary) 
<dt>rb_ary_unshift(VALUE ary, VALUE val) 
<dd>
<p>ary.push, ary.pop, ary.shift, ary.unshift</p>
</dd><dt>rb_ary_cat(VALUE ary, const VALUE *ptr, long len) 
<dd>
<p>Appends len elements of objects from ptr to the array.</p>
</dd></dl>

<h2 id="label-Extending+Ruby+with+C">Extending Ruby with C<span><a href="#label-Extending+Ruby+with+C">&para;</a> <a href="#top">&uarr;</a></span></h2>

<h3 id="label-Adding+new+features+to+Ruby">Adding new features to Ruby<span><a href="#label-Adding+new+features+to+Ruby">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>You can add new features (classes, methods, etc.) to the Ruby interpreter.  Ruby provides APIs for defining the following things:</p>
<ul><li>
<p>Classes, Modules</p>
</li><li>
<p>Methods, singleton methods</p>
</li><li>
<p>Constants</p>
</li></ul>

<h4 id="label-Class+and+Module+Definition"><a href="Class.html"><code>Class</code></a> and <a href="Module.html"><code>Module</code></a> Definition<span><a href="#label-Class+and+Module+Definition">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>To define a class or module, use the functions below:</p>

<pre>VALUE rb_define_class(const char *name, VALUE super)
VALUE rb_define_module(const char *name)</pre>

<p>These functions return the newly created class or module.  You may want to save this reference into a variable to use later.</p>

<p>To define nested classes or modules, use the functions below:</p>

<pre>VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
VALUE rb_define_module_under(VALUE outer, const char *name)</pre>

<h4 id="label-Method+and+singleton+method+definition"><a href="Method.html"><code>Method</code></a> and singleton method definition<span><a href="#label-Method+and+singleton+method+definition">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>To define methods or singleton methods, use these functions:</p>

<pre>void rb_define_method(VALUE klass, const char *name,
                      VALUE (*func)(ANYARGS), int argc)

void rb_define_singleton_method(VALUE object, const char *name,
                                VALUE (*func)(ANYARGS), int argc)</pre>

<p>The ‘argc’ represents the number of the arguments to the C function, which must be less than 17.  But I doubt you’ll need that many.</p>

<p>If ‘argc’ is negative, it specifies the calling sequence, not number of the arguments.</p>

<p>If argc is -1, the function will be called as:</p>

<pre>VALUE func(int argc, VALUE *argv, VALUE obj)</pre>

<p>where argc is the actual number of arguments, argv is the C array of the arguments, and obj is the receiver.</p>

<p>If argc is -2, the arguments are passed in a Ruby array. The function will be called like:</p>

<pre>VALUE func(VALUE obj, VALUE args)</pre>

<p>where obj is the receiver, and args is the Ruby array containing actual arguments.</p>

<p>There are some more functions to define methods. One takes an ID as the name of method to be defined. See also ID or <a href="Symbol.html"><code>Symbol</code></a> below.</p>

<pre>void rb_define_method_id(VALUE klass, ID name,
                         VALUE (*func)(ANYARGS), int argc)</pre>

<p>There are two functions to define private/protected methods:</p>

<pre>void rb_define_private_method(VALUE klass, const char *name,
                              VALUE (*func)(ANYARGS), int argc)
void rb_define_protected_method(VALUE klass, const char *name,
                                VALUE (*func)(ANYARGS), int argc)</pre>

<p>At last, rb_define_module_function defines a module function, which are private AND singleton methods of the module. For example, sqrt is a module function defined in the <a href="Math.html"><code>Math</code></a> module. It can be called in the following way:</p>

<pre class="ruby"><span class="ruby-constant">Math</span>.<span class="ruby-identifier">sqrt</span>(<span class="ruby-value">4</span>)
</pre>

<p>or</p>

<pre class="ruby"><span class="ruby-identifier">include</span> <span class="ruby-constant">Math</span>
<span class="ruby-identifier">sqrt</span>(<span class="ruby-value">4</span>)
</pre>

<p>To define module functions, use:</p>

<pre>void rb_define_module_function(VALUE module, const char *name,
                               VALUE (*func)(ANYARGS), int argc)</pre>

<p>In addition, function-like methods, which are private methods defined in the <a href="Kernel.html"><code>Kernel</code></a> module, can be defined using:</p>

<pre>void rb_define_global_function(const char *name, VALUE (*func)(ANYARGS), int argc)</pre>

<p>To define an alias for the method,</p>

<pre>void rb_define_alias(VALUE module, const char* new, const char* old);</pre>

<p>To define a reader/writer for an attribute,</p>

<pre>void rb_define_attr(VALUE klass, const char *name, int read, int write)</pre>

<p>To define and undefine the ‘allocate’ class method,</p>

<pre>void rb_define_alloc_func(VALUE klass, VALUE (*func)(VALUE klass));
void rb_undef_alloc_func(VALUE klass);</pre>

<p>func has to take the klass as the argument and return a newly allocated instance.  This instance should be as empty as possible, without any expensive (including external) resources.</p>

<p>If you are overriding an existing method of any ancestor of your class, you may rely on:</p>

<pre>VALUE rb_call_super(int argc, const VALUE *argv)</pre>

<p>To specify whether keyword arguments are passed when calling super:</p>

<pre>VALUE rb_call_super_kw(int argc, const VALUE *argv, int kw_splat)</pre>

<p><code>kw_splat</code> can have these possible values (used by all methods that accept <code>kw_splat</code> argument):</p>
<dl class="rdoc-list note-list"><dt>RB_NO_KEYWORDS 
<dd>
<p>Do not pass keywords</p>
</dd><dt>RB_PASS_KEYWORDS 
<dd>
<p>Pass keywords, final argument should be a hash of keywords</p>
</dd><dt>RB_PASS_CALLED_KEYWORDS 
<dd>
<p>Pass keywords if current method was called with keywords, useful for argument delegation</p>
</dd></dl>

<p>To achieve the receiver of the current scope (if no other way is available), you can use:</p>

<pre class="ruby"><span class="ruby-constant">VALUE</span> <span class="ruby-identifier">rb_current_receiver</span>(<span class="ruby-identifier">void</span>)
</pre>

<h4 id="label-Constant+definition">Constant definition<span><a href="#label-Constant+definition">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>We have 2 functions to define constants:</p>

<pre>void rb_define_const(VALUE klass, const char *name, VALUE val)
void rb_define_global_const(const char *name, VALUE val)</pre>

<p>The former is to define a constant under specified class/module.  The latter is to define a global constant.</p>

<h3 id="label-Use+Ruby+features+from+C">Use Ruby features from C<span><a href="#label-Use+Ruby+features+from+C">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>There are several ways to invoke Ruby’s features from C code.</p>

<h4 id="label-Evaluate+Ruby+programs+in+a+string">Evaluate Ruby programs in a string<span><a href="#label-Evaluate+Ruby+programs+in+a+string">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>The easiest way to use Ruby’s functionality from a C program is to evaluate the string as Ruby program.  This function will do the job:</p>

<pre class="ruby"><span class="ruby-constant">VALUE</span> <span class="ruby-identifier">rb_eval_string</span>(<span class="ruby-identifier">const</span> <span class="ruby-identifier">char</span> <span class="ruby-operator">*</span><span class="ruby-identifier">str</span>)
</pre>

<p>Evaluation is done under the current context, thus current local variables of the innermost method (which is defined by Ruby) can be accessed.</p>

<p>Note that the evaluation can raise an exception. There is a safer function:</p>

<pre>VALUE rb_eval_string_protect(const char *str, int *state)</pre>

<p>It returns nil when an error occurred. Moreover, *state is zero if str was successfully evaluated, or nonzero otherwise.</p>

<h4 id="label-ID+or+Symbol">ID or <a href="Symbol.html"><code>Symbol</code></a><span><a href="#label-ID+or+Symbol">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>You can invoke methods directly, without parsing the string.  First I need to explain about ID.  ID is the integer number to represent Ruby’s identifiers such as variable names.  The Ruby data type corresponding to ID is <a href="Symbol.html"><code>Symbol</code></a>.  It can be accessed from Ruby in the form:</p>

<pre class="ruby"><span class="ruby-value">:Identifier</span>
</pre>

<p>or</p>

<pre class="ruby"><span class="ruby-value">:&quot;any kind of string&quot;</span>
</pre>

<p>You can get the ID value from a string within C code by using</p>

<pre class="ruby"><span class="ruby-identifier">rb_intern</span>(<span class="ruby-identifier">const</span> <span class="ruby-identifier">char</span> <span class="ruby-operator">*</span><span class="ruby-identifier">name</span>)
<span class="ruby-identifier">rb_intern_str</span>(<span class="ruby-constant">VALUE</span> <span class="ruby-identifier">name</span>)
</pre>

<p>You can retrieve ID from Ruby object (<a href="Symbol.html"><code>Symbol</code></a> or <a href="String.html"><code>String</code></a>) given as an argument by using</p>

<pre>rb_to_id(VALUE symbol)
rb_check_id(volatile VALUE *name)
rb_check_id_cstr(const char *name, long len, rb_encoding *enc)</pre>

<p>These functions try to convert the argument to a <a href="String.html"><code>String</code></a> if it was not a <a href="Symbol.html"><code>Symbol</code></a> nor a <a href="String.html"><code>String</code></a>.  The second function stores the converted result into *name, and returns 0 if the string is not a known symbol. After this function returned a non-zero value, *name is always a <a href="Symbol.html"><code>Symbol</code></a> or a <a href="String.html"><code>String</code></a>, otherwise it is a <a href="String.html"><code>String</code></a> if the result is 0. The third function takes NUL-terminated C string, not Ruby VALUE.</p>

<p>You can retrieve <a href="Symbol.html"><code>Symbol</code></a> from Ruby object (<a href="Symbol.html"><code>Symbol</code></a> or <a href="String.html"><code>String</code></a>) given as an argument by using</p>

<pre>rb_to_symbol(VALUE name)
rb_check_symbol(volatile VALUE *namep)
rb_check_symbol_cstr(const char *ptr, long len, rb_encoding *enc)</pre>

<p>These functions are similar to above functions except that these return a <a href="Symbol.html"><code>Symbol</code></a> instead of an ID.</p>

<p>You can convert C ID to Ruby <a href="Symbol.html"><code>Symbol</code></a> by using</p>

<pre class="ruby"><span class="ruby-constant">VALUE</span> <span class="ruby-constant">ID2SYM</span>(<span class="ruby-constant">ID</span> <span class="ruby-identifier">id</span>)
</pre>

<p>and to convert Ruby <a href="Symbol.html"><code>Symbol</code></a> object to ID, use</p>

<pre class="ruby"><span class="ruby-constant">ID</span> <span class="ruby-constant">SYM2ID</span>(<span class="ruby-constant">VALUE</span> <span class="ruby-identifier">symbol</span>)
</pre>

<h4 id="label-Invoke+Ruby+method+from+C">Invoke Ruby method from C<span><a href="#label-Invoke+Ruby+method+from+C">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>To invoke methods directly, you can use the function below</p>

<pre>VALUE rb_funcall(VALUE recv, ID mid, int argc, ...)</pre>

<p>This function invokes a method on the recv, with the method name specified by the symbol mid.</p>

<h4 id="label-Accessing+the+variables+and+constants">Accessing the variables and constants<span><a href="#label-Accessing+the+variables+and+constants">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>You can access class variables and instance variables using access functions.  Also, global variables can be shared between both environments.  There’s no way to access Ruby’s local variables.</p>

<p>The functions to access/modify instance variables are below:</p>

<pre>VALUE rb_ivar_get(VALUE obj, ID id)
VALUE rb_ivar_set(VALUE obj, ID id, VALUE val)</pre>

<p>id must be the symbol, which can be retrieved by rb_intern().</p>

<p>To access the constants of the class/module:</p>

<pre>VALUE rb_const_get(VALUE obj, ID id)</pre>

<p>See also Constant Definition above.</p>

<h2 id="label-Information+sharing+between+Ruby+and+C">Information sharing between Ruby and C<span><a href="#label-Information+sharing+between+Ruby+and+C">&para;</a> <a href="#top">&uarr;</a></span></h2>

<h3 id="label-Ruby+constants+that+can+be+accessed+from+C">Ruby constants that can be accessed from C<span><a href="#label-Ruby+constants+that+can+be+accessed+from+C">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>As stated in section 1.3, the following Ruby constants can be referred from C.</p>
<dl class="rdoc-list note-list"><dt>Qtrue 
<dt>Qfalse 
<dd>
<p>Boolean values.  Qfalse is false in C also (i.e. 0).</p>
</dd><dt>Qnil 
<dd>
<p>Ruby nil in C scope.</p>
</dd></dl>

<h3 id="label-Global+variables+shared+between+C+and+Ruby">Global variables shared between C and Ruby<span><a href="#label-Global+variables+shared+between+C+and+Ruby">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>Information can be shared between the two environments using shared global variables.  To define them, you can use functions listed below:</p>

<pre>void rb_define_variable(const char *name, VALUE *var)</pre>

<p>This function defines the variable which is shared by both environments. The value of the global variable pointed to by ‘var’ can be accessed through Ruby’s global variable named ‘name’.</p>

<p>You can define read-only (from Ruby, of course) variables using the function below.</p>

<pre>void rb_define_readonly_variable(const char *name, VALUE *var)</pre>

<p>You can define hooked variables.  The accessor functions (getter and setter) are called on access to the hooked variables.</p>

<pre>void rb_define_hooked_variable(const char *name, VALUE *var,
                               VALUE (*getter)(), void (*setter)())</pre>

<p>If you need to supply either setter or getter, just supply 0 for the hook you don’t need.  If both hooks are 0, rb_define_hooked_variable() works just like rb_define_variable().</p>

<p>The prototypes of the getter and setter functions are as follows:</p>

<pre>VALUE (*getter)(ID id, VALUE *var);
void (*setter)(VALUE val, ID id, VALUE *var);</pre>

<p>Also you can define a Ruby global variable without a corresponding C variable.  The value of the variable will be set/get only by hooks.</p>

<pre>void rb_define_virtual_variable(const char *name,
                                VALUE (*getter)(), void (*setter)())</pre>

<p>The prototypes of the getter and setter functions are as follows:</p>

<pre>VALUE (*getter)(ID id);
void (*setter)(VALUE val, ID id);</pre>

<h3 id="label-Encapsulate+C+data+into+a+Ruby+object">Encapsulate C data into a Ruby object<span><a href="#label-Encapsulate+C+data+into+a+Ruby+object">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>Sometimes you need to expose your struct in the C world as a Ruby object. In a situation like this, making use of the TypedData_XXX macro family, the pointer to the struct and the Ruby object can be mutually converted.</p>

<h4 id="label-C+struct+to+Ruby+object">C struct to Ruby object<span><a href="#label-C+struct+to+Ruby+object">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>You can convert sval, a pointer to your struct, into a Ruby object with the next macro.</p>

<pre class="ruby"><span class="ruby-constant">TypedData_Wrap_Struct</span>(<span class="ruby-identifier">klass</span>, <span class="ruby-identifier">data_type</span>, <span class="ruby-identifier">sval</span>)
</pre>

<p>TypedData_Wrap_Struct() returns a created Ruby object as a VALUE.</p>

<p>The klass argument is the class for the object.  The klass should derive from rb_cObject, and the allocator must be set by calling rb_define_alloc_func or rb_undef_alloc_func.</p>

<p>data_type is a pointer to a const rb_data_type_t which describes how Ruby should manage the struct.</p>

<p>rb_data_type_t is defined like this.  Let’s take a look at each member of the struct.</p>

<pre>typedef struct rb_data_type_struct rb_data_type_t;

struct rb_data_type_struct {
    const char *wrap_struct_name;
    struct {
        void (*dmark)(void*);
        void (*dfree)(void*);
        size_t (*dsize)(const void *);
        void (*dcompact)(void*);
        void *reserved[1];
    } function;
    const rb_data_type_t *parent;
    void *data;
    VALUE flags;
};</pre>

<p>wrap_struct_name is an identifier of this instance of the struct. It is basically used for collecting and emitting statistics. So the identifier must be unique in the process, but doesn’t need to be valid as a C or Ruby identifier.</p>

<p>These dmark / dfree functions are invoked during <a href="GC.html"><code>GC</code></a> execution.  No object allocations are allowed during it, so do not allocate ruby objects inside them.</p>

<p>dmark is a function to mark Ruby objects referred from your struct. It must mark all references from your struct with rb_gc_mark or its family if your struct keeps such references.</p>

<p>dfree is a function to free the pointer allocation. If this is RUBY_DEFAULT_FREE, the pointer will be just freed.</p>

<p>dsize calculates memory consumption in bytes by the struct. Its parameter is a pointer to your struct. You can pass 0 as dsize if it is hard to implement such a function. But it is still recommended to avoid 0.</p>

<p>dcompact is invoked when memory compaction took place. Referred Ruby objects that were marked by rb_gc_mark_movable() can here be updated per rb_gc_location().</p>

<p>You have to fill reserved with 0.</p>

<p>parent can point to another C type definition that the Ruby object is inherited from. Then TypedData_Get_Struct() does also accept derived objects.</p>

<p>You can fill “data” with an arbitrary value for your use. Ruby does nothing with the member.</p>

<p>flags is a bitwise-OR of the following flag values. Since they require deep understanding of garbage collector in Ruby, you can just set 0 to flags if you are not sure.</p>
<dl class="rdoc-list note-list"><dt>RUBY_TYPED_FREE_IMMEDIATELY 
<dd>
<p>This flag makes the garbage collector immediately invoke dfree() during <a href="GC.html"><code>GC</code></a> when it need to free your struct. You can specify this flag if the dfree never unlocks Ruby’s internal lock (GVL).</p>

<p>If this flag is not set, Ruby defers invocation of dfree() and invokes dfree() at the same time as finalizers.</p>
</dd><dt>RUBY_TYPED_WB_PROTECTED 
<dd>
<p>It shows that implementation of the object supports write barriers. If this flag is set, Ruby is better able to do garbage collection of the object.</p>

<p>When it is set, however, you are responsible for putting write barriers in all implementations of methods of that object as appropriate. Otherwise Ruby might crash while running.</p>

<p>More about write barriers can be found in “Generational GC” in Appendix D.</p>
</dd><dt>RUBY_TYPED_FROZEN_SHAREABLE 
<dd>
<p>This flag indicates that the object is shareable object if the object is frozen. See Appendix F more details.</p>

<p>If this flag is not set, the object can not become a shareable object by <a href="Ractor.html#method-c-make_shareable"><code>Ractor.make_shareable()</code></a> method.</p>
</dd></dl>

<p>You can allocate and wrap the structure in one step.</p>

<pre class="ruby"><span class="ruby-constant">TypedData_Make_Struct</span>(<span class="ruby-identifier">klass</span>, <span class="ruby-identifier">type</span>, <span class="ruby-identifier">data_type</span>, <span class="ruby-identifier">sval</span>)
</pre>

<p>This macro returns an allocated T_DATA object, wrapping the pointer to the structure, which is also allocated.  This macro works like:</p>

<pre class="ruby">(<span class="ruby-identifier">sval</span> = <span class="ruby-constant">ZALLOC</span>(<span class="ruby-identifier">type</span>), <span class="ruby-constant">TypedData_Wrap_Struct</span>(<span class="ruby-identifier">klass</span>, <span class="ruby-identifier">data_type</span>, <span class="ruby-identifier">sval</span>))
</pre>

<p>Arguments klass and data_type work like their counterparts in TypedData_Wrap_Struct().  A pointer to the allocated structure will be assigned to sval, which should be a pointer of the type specified.</p>

<h4 id="label-Declaratively+marking-2Fcompacting+struct+references">Declaratively marking/compacting struct references<span><a href="#label-Declaratively+marking-2Fcompacting+struct+references">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>In the case where your struct refers to Ruby objects that are simple values, not wrapped in conditional logic or complex data structures an alternative approach to marking and reference updating is provided, by declaring offset references to the VALUES in your struct.</p>

<p>Doing this allows the Ruby <a href="GC.html"><code>GC</code></a> to support marking these references and <a href="GC.html"><code>GC</code></a> compaction without the need to define the ‘dmark` and `dcompact` callbacks.</p>

<p>You must define a static list of VALUE pointers to the offsets within your struct where the references are located, and set the “data” member to point to this reference list. The reference list must end with ‘END_REFS`</p>

<p>Some Macros have been provided to make edge referencing easier:</p>
<ul><li>
<p><code>RUBY_TYPED_DECL_MARKING</code> =A flag that can be set on the ‘ruby_data_type_t` to indicate that references are being declared as edges.</p>
</li><li>
<p><code>RUBY_REFERENCES_START(ref_list_name)</code> - Define ‘ref_list_name` as a list of references</p>
</li><li>
<p><code>RUBY_REFERENCES_END</code> - Mark the end of the references list. This will take care of terminating the list correctly</p>
</li><li>
<p><code>RUBY_REF_EDGE\(struct, member\)</code> - Declare ‘member` as a VALUE edge from `struct`. Use this after `RUBY_REFERENCES_START`</p>
</li><li>
<p><code>REFS_LIST_PTR</code> - Coerce the reference list into a format that can be accepted by the existing ‘dmark` interface.</p>
</li></ul>

<p>The example below is from ‘Dir` (defined in `dir.c`)</p>

<pre>// The struct being wrapped. Notice this contains 3 members of which the second
// is a VALUE reference to another ruby object.
struct dir_data {
    DIR *dir;
    const VALUE path;
    rb_encoding *enc;
}

// Define a reference list `dir_refs` containing a single entry to `path`, and
// terminating with RUBY_REF_END
RUBY_REFERENCES_START(dir_refs)
    REF_EDGE(dir_data, path),
RUBY_REFERENCES_END

// Override the &quot;dmark&quot; field with the defined reference list now that we
// no longer need a marking callback and add RUBY_TYPED_DECL_MARKING to the
// flags field
static const rb_data_type_t dir_data_type = {
    &quot;dir&quot;,
    {REFS_LIST_PTR(dir_refs), dir_free, dir_memsize,},
    0, NULL, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_DECL_MARKING
};</pre>

<p>Declaring simple references declaratively in this manner allows the <a href="GC.html"><code>GC</code></a> to both mark, and move the underlying object, and automatically update the reference to it during compaction.</p>

<h4 id="label-Ruby+object+to+C+struct">Ruby object to C struct<span><a href="#label-Ruby+object+to+C+struct">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>To retrieve the C pointer from the T_DATA object, use the macro TypedData_Get_Struct().</p>

<pre>TypedData_Get_Struct(obj, type, &amp;data_type, sval)</pre>

<p>A pointer to the structure will be assigned to the variable sval.</p>

<p>See the example below for details.</p>

<h2 id="label-Example+-+Creating+the+dbm+Extension">Example - Creating the dbm Extension<span><a href="#label-Example+-+Creating+the+dbm+Extension">&para;</a> <a href="#top">&uarr;</a></span></h2>

<p>OK, here’s the example of making an extension library.  This is the extension to access DBMs.  The full source is included in the ext/ directory in the Ruby’s source tree.</p>

<h3 id="label-Make+the+directory">Make the directory<span><a href="#label-Make+the+directory">&para;</a> <a href="#top">&uarr;</a></span></h3>

<pre>% mkdir ext/dbm</pre>

<p>Make a directory for the extension library under ext directory.</p>

<h3 id="label-Design+the+Library">Design the Library<span><a href="#label-Design+the+Library">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>You need to design the library features, before making it.</p>

<h3 id="label-Write+the+C+Code">Write the C Code<span><a href="#label-Write+the+C+Code">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>You need to write C code for your extension library.  If your library has only one source file, choosing “LIBRARY.c” as a file name is preferred.  On the other hand, in case your library has multiple source files, avoid choosing “LIBRARY.c” for a file name.  It may conflict with an intermediate file “LIBRARY.o” on some platforms. Note that some functions in mkmf library described below generate a file “conftest.c” for checking with compilation.  You shouldn’t choose “conftest.c” as a name of a source file.</p>

<p>Ruby will execute the initializing function named “Init_LIBRARY” in the library.  For example, “Init_dbm()” will be executed when loading the library.</p>

<p>Here’s the example of an initializing function.</p>

<pre>#include &lt;ruby.h&gt;
void
Init_dbm(void)
{
    /* define DBM class */
    VALUE cDBM = rb_define_class(&quot;DBM&quot;, rb_cObject);
    /* Redefine DBM.allocate
    rb_define_alloc_func(cDBM, fdbm_alloc);
    /* DBM includes Enumerable module */
    rb_include_module(cDBM, rb_mEnumerable);

    /* DBM has class method open(): arguments are received as C array */
    rb_define_singleton_method(cDBM, &quot;open&quot;, fdbm_s_open, -1);

    /* DBM instance method close(): no args */
    rb_define_method(cDBM, &quot;close&quot;, fdbm_close, 0);
    /* DBM instance method []: 1 argument */
    rb_define_method(cDBM, &quot;[]&quot;, fdbm_aref, 1);

    /* ... */

    /* ID for a instance variable to store DBM data */
    id_dbm = rb_intern(&quot;dbm&quot;);
}</pre>

<p>The dbm extension wraps the dbm struct in the C environment using TypedData_Make_Struct.</p>

<pre>struct dbmdata {
    int  di_size;
    DBM *di_dbm;
};

static const rb_data_type_t dbm_type = {
    &quot;dbm&quot;,
    {0, free_dbm, memsize_dbm,},
    0, 0,
    RUBY_TYPED_FREE_IMMEDIATELY,
};

static VALUE
fdbm_alloc(VALUE klass)
{
    struct dbmdata *dbmp;
    /* Allocate T_DATA object and C struct and fill struct with zero bytes */
    return TypedData_Make_Struct(klass, struct dbmdata, &amp;dbm_type, dbmp);
}</pre>

<p>This code wraps the dbmdata structure into a Ruby object.  We avoid wrapping DBM* directly, because we want to cache size information. Since Object.allocate allocates an ordinary T_OBJECT type (instead of T_DATA), it’s important to either use rb_define_alloc_func() to overwrite it or rb_undef_alloc_func() to delete it.</p>

<p>To retrieve the dbmdata structure from a Ruby object, we define the following macro:</p>

<pre>#define GetDBM(obj, dbmp) do {\
    TypedData_Get_Struct((obj), struct dbmdata, &amp;dbm_type, (dbmp));\
    if ((dbmp) == 0) closed_dbm();\
    if ((dbmp)-&gt;di_dbm == 0) closed_dbm();\
} while (0)</pre>

<p>This sort of complicated macro does the retrieving and close checking for the DBM.</p>

<p>There are three kinds of way to receive method arguments.  First, methods with a fixed number of arguments receive arguments like this:</p>

<pre>static VALUE
fdbm_aref(VALUE obj, VALUE keystr)
{
    struct dbmdata *dbmp;
    GetDBM(obj, dbmp);
    /* Use dbmp to access the key */
    dbm_fetch(dbmp-&gt;di_dbm, StringValueCStr(keystr));
    /* ... */
}</pre>

<p>The first argument of the C function is the self, the rest are the arguments to the method.</p>

<p>Second, methods with an arbitrary number of arguments receive arguments like this:</p>

<pre>static VALUE
fdbm_s_open(int argc, VALUE *argv, VALUE klass)
{
    /* ... */
    if (rb_scan_args(argc, argv, &quot;11&quot;, &amp;file, &amp;vmode) == 1) {
        mode = 0666;          /* default value */
    }
    /* ... */
}</pre>

<p>The first argument is the number of method arguments, the second argument is the C array of the method arguments, and the third argument is the receiver of the method.</p>

<p>You can use the function rb_scan_args() to check and retrieve the arguments.  The third argument is a string that specifies how to capture method arguments and assign them to the following VALUE references.</p>

<p>You can just check the argument number with rb_check_arity(), this is handy in the case you want to treat the arguments as a list.</p>

<p>The following is an example of a method that takes arguments by Ruby’s array:</p>

<pre>static VALUE
thread_initialize(VALUE thread, VALUE args)
{
    /* ... */
}</pre>

<p>The first argument is the receiver, the second one is the Ruby array which contains the arguments to the method.</p>

<p><strong>Notice</strong>: <a href="GC.html"><code>GC</code></a> should know about global variables which refer to Ruby’s objects, but are not exported to the Ruby world.  You need to protect them by</p>

<pre class="ruby"><span class="ruby-identifier">void</span> <span class="ruby-identifier">rb_global_variable</span>(<span class="ruby-constant">VALUE</span> <span class="ruby-operator">*</span><span class="ruby-identifier">var</span>)
</pre>

<p>or the objects themselves by</p>

<pre class="ruby"><span class="ruby-identifier">void</span> <span class="ruby-identifier">rb_gc_register_mark_object</span>(<span class="ruby-constant">VALUE</span> <span class="ruby-identifier">object</span>)
</pre>

<h3 id="label-Prepare+extconf.rb">Prepare extconf.rb<span><a href="#label-Prepare+extconf.rb">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>If the file named extconf.rb exists, it will be executed to generate Makefile.</p>

<p>extconf.rb is the file for checking compilation conditions etc.  You need to put</p>

<pre class="ruby"><span class="ruby-identifier">require</span> <span class="ruby-string">&#39;mkmf&#39;</span>
</pre>

<p>at the top of the file.  You can use the functions below to check various conditions.</p>

<pre>append_cppflags(array-of-flags[, opt]): append each flag to $CPPFLAGS if usable
append_cflags(array-of-flags[, opt]): append each flag to $CFLAGS if usable
append_ldflags(array-of-flags[, opt]): append each flag to $LDFLAGS if usable
have_macro(macro[, headers[, opt]]): check whether macro is defined
have_library(lib[, func[, headers[, opt]]]): check whether library containing function exists
find_library(lib[, func, *paths]): find library from paths
have_func(func[, headers[, opt]): check whether function exists
have_var(var[, headers[, opt]]): check whether variable exists
have_header(header[, preheaders[, opt]]): check whether header file exists
find_header(header, *paths): find header from paths
have_framework(fw): check whether framework exists (for MacOS X)
have_struct_member(type, member[, headers[, opt]]): check whether struct has member
have_type(type[, headers[, opt]]): check whether type exists
find_type(type, opt, *headers): check whether type exists in headers
have_const(const[, headers[, opt]]): check whether constant is defined
check_sizeof(type[, headers[, opts]]): check size of type
check_signedness(type[, headers[, opts]]): check signedness of type
convertible_int(type[, headers[, opts]]): find convertible integer type
find_executable(bin[, path]): find executable file path
create_header(header): generate configured header
create_makefile(target[, target_prefix]): generate Makefile</pre>

<p>See MakeMakefile for full documentation of these functions.</p>

<p>The value of the variables below will affect the Makefile.</p>

<pre>$CFLAGS: included in CFLAGS make variable (such as -O)
$CPPFLAGS: included in CPPFLAGS make variable (such as -I, -D)
$LDFLAGS: included in LDFLAGS make variable (such as -L)
$objs: list of object file names</pre>

<p>Compiler/linker flags are not portable usually, you should use <code>append_cppflags</code>, <code>append_cpflags</code> and <code>append_ldflags</code> respectively instead of appending the above variables directly.</p>

<p>Normally, the object files list is automatically generated by searching source files, but you must define them explicitly if any sources will be generated while building.</p>

<p>If a compilation condition is not fulfilled, you should not call “create_makefile”.  The Makefile will not be generated, compilation will not be done.</p>

<h3 id="label-Prepare+depend+-28Optional-29">Prepare depend (Optional)<span><a href="#label-Prepare+depend+-28Optional-29">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>If the file named depend exists, Makefile will include that file to check dependencies.  You can make this file by invoking</p>

<pre>% gcc -MM *.c &gt; depend</pre>

<p>It’s harmless.  Prepare it.</p>

<h3 id="label-Generate+Makefile">Generate Makefile<span><a href="#label-Generate+Makefile">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>Try generating the Makefile by:</p>

<pre class="ruby"><span class="ruby-identifier">ruby</span> <span class="ruby-identifier">extconf</span>.<span class="ruby-identifier">rb</span>
</pre>

<p>If the library should be installed under vendor_ruby directory instead of site_ruby directory, use –vendor option as follows.</p>

<pre class="ruby"><span class="ruby-identifier">ruby</span> <span class="ruby-identifier">extconf</span>.<span class="ruby-identifier">rb</span> <span class="ruby-operator">-</span><span class="ruby-operator">-</span><span class="ruby-identifier">vendor</span>
</pre>

<p>You don’t need this step if you put the extension library under the ext directory of the ruby source tree.  In that case, compilation of the interpreter will do this step for you.</p>

<h3 id="label-Run+make">Run make<span><a href="#label-Run+make">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>Type</p>

<pre class="ruby"><span class="ruby-identifier">make</span>
</pre>

<p>to compile your extension.  You don’t need this step either if you have put the extension library under the ext directory of the ruby source tree.</p>

<h3 id="label-Debug">Debug<span><a href="#label-Debug">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>You may need to rb_debug the extension.  Extensions can be linked statically by adding the directory name in the ext/Setup file so that you can inspect the extension with the debugger.</p>

<h3 id="label-Done-21+Now+you+have+the+extension+library">Done! Now you have the extension library<span><a href="#label-Done-21+Now+you+have+the+extension+library">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>You can do anything you want with your library.  The author of Ruby will not claim any restrictions on your code depending on the Ruby API. Feel free to use, modify, distribute or sell your program.</p>

<h2 id="label-Appendix+A.+Ruby+header+and+source+files+overview">Appendix A. Ruby header and source files overview<span><a href="#label-Appendix+A.+Ruby+header+and+source+files+overview">&para;</a> <a href="#top">&uarr;</a></span></h2>

<h3 id="label-Ruby+header+files">Ruby header files<span><a href="#label-Ruby+header+files">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>Everything under <code>$repo_root/include/ruby</code> is installed with <code>make install</code>. It should be included per <code>#include &lt;ruby.h&gt;</code> from C extensions. All symbols are public API with the exception of symbols prefixed with <code>rbimpl_</code> or <code>RBIMPL_</code>. They are implementation details and shouldn’t be used by C extensions.</p>

<p>Only <code>$repo_root/include/ruby/*.h</code> whose corresponding macros are defined in the <code>$repo_root/include/ruby.h</code> header are allowed to be <code>#include</code>-d by C extensions.</p>

<p>Header files under <code>$repo_root/internal/</code> or directly under the root <code>$repo_root/*.h</code> are not make-installed. They are internal headers with only internal APIs.</p>

<h3 id="label-Ruby+language+core">Ruby language core<span><a href="#label-Ruby+language+core">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>class.c    
<dd>
<p>classes and modules</p>
</dd><dt>error.c    
<dd>
<p>exception classes and exception mechanism</p>
</dd><dt>gc.c       
<dd>
<p>memory management</p>
</dd><dt>load.c     
<dd>
<p>library loading</p>
</dd><dt>object.c   
<dd>
<p>objects</p>
</dd><dt>variable.c 
<dd>
<p>variables and constants</p>
</dd></dl>

<h3 id="label-Ruby+syntax+parser">Ruby syntax parser<span><a href="#label-Ruby+syntax+parser">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>parse.y       
<dd>
<p>grammar definition</p>
</dd><dt>parse.c       
<dd>
<p>automatically generated from parse.y</p>
</dd><dt>defs/keywords 
<dd>
<p>reserved keywords</p>
</dd><dt>lex.c         
<dd>
<p>automatically generated from keywords</p>
</dd></dl>

<h3 id="label-Ruby+evaluator+-28a.k.a.+YARV-29">Ruby evaluator (a.k.a. YARV)<span><a href="#label-Ruby+evaluator+-28a.k.a.+YARV-29">&para;</a> <a href="#top">&uarr;</a></span></h3>

<pre>compile.c
eval.c
eval_error.c
eval_jump.c
eval_safe.c
insns.def           : definition of VM instructions
iseq.c              : implementation of VM::ISeq
thread.c            : thread management and context switching
thread_win32.c      : thread implementation
thread_pthread.c    : ditto
vm.c
vm_dump.c
vm_eval.c
vm_exec.c
vm_insnhelper.c
vm_method.c

defs/opt_insns_unif.def  : instruction unification
defs/opt_operand.def     : definitions for optimization

  -&gt; insn*.inc           : automatically generated
  -&gt; opt*.inc            : automatically generated
  -&gt; vm.inc              : automatically generated</pre>

<h3 id="label-Regular+expression+engine+-28Onigumo-29">Regular expression engine (Onigumo)<span><a href="#label-Regular+expression+engine+-28Onigumo-29">&para;</a> <a href="#top">&uarr;</a></span></h3>

<pre class="ruby"><span class="ruby-identifier">regcomp</span>.<span class="ruby-identifier">c</span>
<span class="ruby-identifier">regenc</span>.<span class="ruby-identifier">c</span>
<span class="ruby-identifier">regerror</span>.<span class="ruby-identifier">c</span>
<span class="ruby-identifier">regexec</span>.<span class="ruby-identifier">c</span>
<span class="ruby-identifier">regparse</span>.<span class="ruby-identifier">c</span>
<span class="ruby-identifier">regsyntax</span>.<span class="ruby-identifier">c</span>
</pre>

<h3 id="label-Utility+functions">Utility functions<span><a href="#label-Utility+functions">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>debug.c    
<dd>
<p>debug symbols for C debugger</p>
</dd><dt>dln.c      
<dd>
<p>dynamic loading</p>
</dd><dt>st.c       
<dd>
<p>general purpose hash table</p>
</dd><dt>strftime.c 
<dd>
<p>formatting times</p>
</dd><dt>util.c     
<dd>
<p>misc utilities</p>
</dd></dl>

<h3 id="label-Ruby+interpreter+implementation">Ruby interpreter implementation<span><a href="#label-Ruby+interpreter+implementation">&para;</a> <a href="#top">&uarr;</a></span></h3>

<pre class="ruby"><span class="ruby-identifier">dmyext</span>.<span class="ruby-identifier">c</span>
<span class="ruby-identifier">dmydln</span>.<span class="ruby-identifier">c</span>
<span class="ruby-identifier">dmyencoding</span>.<span class="ruby-identifier">c</span>
<span class="ruby-identifier">id</span>.<span class="ruby-identifier">c</span>
<span class="ruby-identifier">inits</span>.<span class="ruby-identifier">c</span>
<span class="ruby-identifier">main</span>.<span class="ruby-identifier">c</span>
<span class="ruby-identifier">ruby</span>.<span class="ruby-identifier">c</span>
<span class="ruby-identifier">version</span>.<span class="ruby-identifier">c</span>

<span class="ruby-identifier">gem_prelude</span>.<span class="ruby-identifier">rb</span>
<span class="ruby-identifier">prelude</span>.<span class="ruby-identifier">rb</span>
</pre>

<h3 id="label-Class+library"><a href="Class.html"><code>Class</code></a> library<span><a href="#label-Class+library">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>array.c      
<dd>
<p><a href="Array.html"><code>Array</code></a></p>
</dd><dt>bignum.c     
<dd>
<p>Bignum</p>
</dd><dt>compar.c     
<dd>
<p><a href="Comparable.html"><code>Comparable</code></a></p>
</dd><dt>complex.c    
<dd>
<p><a href="Complex.html"><code>Complex</code></a></p>
</dd><dt>cont.c       
<dd>
<p><a href="Fiber.html"><code>Fiber</code></a>, <a href="Continuation.html"><code>Continuation</code></a></p>
</dd><dt>dir.c        
<dd>
<p><a href="Dir.html"><code>Dir</code></a></p>
</dd><dt>enum.c       
<dd>
<p><a href="Enumerable.html"><code>Enumerable</code></a></p>
</dd><dt>enumerator.c 
<dd>
<p><a href="Enumerator.html"><code>Enumerator</code></a></p>
</dd><dt>file.c       
<dd>
<p><a href="File.html"><code>File</code></a></p>
</dd><dt>hash.c       
<dd>
<p><a href="Hash.html"><code>Hash</code></a></p>
</dd><dt>io.c         
<dd>
<p><a href="IO.html"><code>IO</code></a></p>
</dd><dt>marshal.c    
<dd>
<p><a href="Marshal.html"><code>Marshal</code></a></p>
</dd><dt>math.c       
<dd>
<p><a href="Math.html"><code>Math</code></a></p>
</dd><dt>numeric.c    
<dd>
<p><a href="Numeric.html"><code>Numeric</code></a>, <a href="Integer.html"><code>Integer</code></a>, Fixnum, <a href="Float.html"><code>Float</code></a></p>
</dd><dt>pack.c       
<dd>
<p><a href="Array.html#method-i-pack"><code>Array#pack</code></a>, <a href="String.html#method-i-unpack"><code>String#unpack</code></a></p>
</dd><dt>proc.c       
<dd>
<p><a href="Binding.html"><code>Binding</code></a>, <a href="Proc.html"><code>Proc</code></a></p>
</dd><dt>process.c    
<dd>
<p><a href="Process.html"><code>Process</code></a></p>
</dd><dt>random.c     
<dd>
<p>random number</p>
</dd><dt>range.c      
<dd>
<p><a href="Range.html"><code>Range</code></a></p>
</dd><dt>rational.c   
<dd>
<p><a href="Rational.html"><code>Rational</code></a></p>
</dd><dt>re.c         
<dd>
<p><a href="Regexp.html"><code>Regexp</code></a>, <a href="MatchData.html"><code>MatchData</code></a></p>
</dd><dt>signal.c     
<dd>
<p><a href="Signal.html"><code>Signal</code></a></p>
</dd><dt>sprintf.c    
<dd>
<p><a href="Kernel.html#method-i-sprintf"><code>String#sprintf</code></a></p>
</dd><dt>string.c     
<dd>
<p><a href="String.html"><code>String</code></a></p>
</dd><dt>struct.c     
<dd>
<p><a href="Struct.html"><code>Struct</code></a></p>
</dd><dt>time.c       
<dd>
<p><a href="Time.html"><code>Time</code></a></p>
</dd><dt>defs/known_errors.def 
<dd>
<p>Errno::* exception classes</p>
</dd><dt>-&gt; known_errors.inc   
<dd>
<p>automatically generated</p>
</dd></dl>

<h3 id="label-Multilingualization">Multilingualization<span><a href="#label-Multilingualization">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>encoding.c  
<dd>
<p><a href="Encoding.html"><code>Encoding</code></a></p>
</dd><dt>transcode.c 
<dd>
<p><a href="Encoding/Converter.html"><code>Encoding::Converter</code></a></p>
</dd><dt>enc/*.c     
<dd>
<p>encoding classes</p>
</dd><dt>enc/trans/* 
<dd>
<p>codepoint mapping tables</p>
</dd></dl>

<h3 id="label-goruby+interpreter+implementation">goruby interpreter implementation<span><a href="#label-goruby+interpreter+implementation">&para;</a> <a href="#top">&uarr;</a></span></h3>

<pre>goruby.c
golf_prelude.rb     : goruby specific libraries.
  -&gt; golf_prelude.c : automatically generated</pre>

<h2 id="label-Appendix+B.+Ruby+extension+API+reference">Appendix B. Ruby extension API reference<span><a href="#label-Appendix+B.+Ruby+extension+API+reference">&para;</a> <a href="#top">&uarr;</a></span></h2>

<h3 id="label-Types">Types<span><a href="#label-Types">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>VALUE 
<dd>
<p>The type for the Ruby object.  Actual structures are defined in ruby.h, such as struct RString, etc.  To refer the values in structures, use casting macros like RSTRING(obj).</p>
</dd></dl>

<h3 id="label-Variables+and+constants">Variables and constants<span><a href="#label-Variables+and+constants">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>Qnil 
<dd>
<p>nil object</p>
</dd><dt>Qtrue 
<dd>
<p>true object (default true value)</p>
</dd><dt>Qfalse 
<dd>
<p>false object</p>
</dd></dl>

<h3 id="label-C+pointer+wrapping">C pointer wrapping<span><a href="#label-C+pointer+wrapping">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>Data_Wrap_Struct(VALUE klass, void (*mark)(), void (*free)(), void *sval) 
<dd>
<p>Wrap a C pointer into a Ruby object.  If object has references to other Ruby objects, they should be marked by using the mark function during the <a href="GC.html"><code>GC</code></a> process.  Otherwise, mark should be 0.  When this object is no longer referred by anywhere, the pointer will be discarded by free function.</p>
</dd><dt>Data_Make_Struct(klass, type, mark, free, sval) 
<dd>
<p>This macro allocates memory using malloc(), assigns it to the variable sval, and returns the DATA encapsulating the pointer to memory region.</p>
</dd><dt>Data_Get_Struct(data, type, sval) 
<dd>
<p>This macro retrieves the pointer value from DATA, and assigns it to the variable sval.</p>
</dd></dl>

<h3 id="label-Checking+VALUE+types">Checking VALUE types<span><a href="#label-Checking+VALUE+types">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>RB_TYPE_P(value, type) 
<dd>
<p>Is <code>value</code> an internal type (T_NIL, T_FIXNUM, etc.)?</p>
</dd><dt>TYPE(value) 
<dd>
<p>Internal type (T_NIL, T_FIXNUM, etc.)</p>
</dd><dt>FIXNUM_P(value) 
<dd>
<p>Is <code>value</code> a Fixnum?</p>
</dd><dt>NIL_P(value) 
<dd>
<p>Is <code>value</code> nil?</p>
</dd><dt>RB_INTEGER_TYPE_P(value) 
<dd>
<p>Is <code>value</code> an <a href="Integer.html"><code>Integer</code></a>?</p>
</dd><dt>RB_FLOAT_TYPE_P(value) 
<dd>
<p>Is <code>value</code> a <a href="Float.html"><code>Float</code></a>?</p>
</dd><dt>void Check_Type(VALUE value, int type) 
<dd>
<p>Ensures <code>value</code> is of the given internal <code>type</code> or raises a <a href="TypeError.html"><code>TypeError</code></a></p>
</dd></dl>

<h3 id="label-VALUE+type+conversion">VALUE type conversion<span><a href="#label-VALUE+type+conversion">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>FIX2INT(value), INT2FIX(i) 
<dd>
<p>Fixnum &lt;-&gt; integer</p>
</dd><dt>FIX2LONG(value), LONG2FIX(l) 
<dd>
<p>Fixnum &lt;-&gt; long</p>
</dd><dt>NUM2INT(value), INT2NUM(i) 
<dd>
<p><a href="Numeric.html"><code>Numeric</code></a> &lt;-&gt; integer</p>
</dd><dt>NUM2UINT(value), UINT2NUM(ui) 
<dd>
<p><a href="Numeric.html"><code>Numeric</code></a> &lt;-&gt; unsigned integer</p>
</dd><dt>NUM2LONG(value), LONG2NUM(l) 
<dd>
<p><a href="Numeric.html"><code>Numeric</code></a> &lt;-&gt; long</p>
</dd><dt>NUM2ULONG(value), ULONG2NUM(ul) 
<dd>
<p><a href="Numeric.html"><code>Numeric</code></a> &lt;-&gt; unsigned long</p>
</dd><dt>NUM2LL(value), LL2NUM(ll) 
<dd>
<p><a href="Numeric.html"><code>Numeric</code></a> &lt;-&gt; long long</p>
</dd><dt>NUM2ULL(value), ULL2NUM(ull) 
<dd>
<p><a href="Numeric.html"><code>Numeric</code></a> &lt;-&gt; unsigned long long</p>
</dd><dt>NUM2OFFT(value), OFFT2NUM(off) 
<dd>
<p><a href="Numeric.html"><code>Numeric</code></a> &lt;-&gt; off_t</p>
</dd><dt>NUM2SIZET(value), SIZET2NUM(size) 
<dd>
<p><a href="Numeric.html"><code>Numeric</code></a> &lt;-&gt; size_t</p>
</dd><dt>NUM2SSIZET(value), SSIZET2NUM(ssize) 
<dd>
<p><a href="Numeric.html"><code>Numeric</code></a> &lt;-&gt; ssize_t</p>
</dd><dt>rb_integer_pack(value, words, numwords, wordsize, nails, flags), rb_integer_unpack(words, numwords, wordsize, nails, flags) 
<dd>
<p><a href="Numeric.html"><code>Numeric</code></a> &lt;-&gt; Arbitrary size integer buffer</p>
</dd><dt>NUM2DBL(value) 
<dd>
<p><a href="Numeric.html"><code>Numeric</code></a> -&gt; double</p>
</dd><dt>rb_float_new(f) 
<dd>
<p>double -&gt; <a href="Float.html"><code>Float</code></a></p>
</dd><dt>RSTRING_LEN(str) 
<dd>
<p><a href="String.html"><code>String</code></a> -&gt; length of <a href="String.html"><code>String</code></a> data in bytes</p>
</dd><dt>RSTRING_PTR(str) 
<dd>
<p><a href="String.html"><code>String</code></a> -&gt; pointer to <a href="String.html"><code>String</code></a> data Note that the result pointer may not be NUL-terminated</p>
</dd><dt>StringValue(value) 
<dd>
<p><a href="Object.html"><code>Object</code></a> with #to_str -&gt; <a href="String.html"><code>String</code></a></p>
</dd><dt>StringValuePtr(value) 
<dd>
<p><a href="Object.html"><code>Object</code></a> with #to_str -&gt; pointer to <a href="String.html"><code>String</code></a> data</p>
</dd><dt>StringValueCStr(value) 
<dd>
<p><a href="Object.html"><code>Object</code></a> with #to_str -&gt; pointer to <a href="String.html"><code>String</code></a> data without NUL bytes It is guaranteed that the result data is NUL-terminated</p>
</dd><dt>rb_str_new2(s) 
<dd>
<p>char * -&gt; <a href="String.html"><code>String</code></a></p>
</dd></dl>

<h3 id="label-Defining+classes+and+modules">Defining classes and modules<span><a href="#label-Defining+classes+and+modules">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>VALUE rb_define_class(const char *name, VALUE super) 
<dd>
<p>Defines a new Ruby class as a subclass of super.</p>
</dd><dt>VALUE rb_define_class_under(VALUE module, const char *name, VALUE super) 
<dd>
<p>Creates a new Ruby class as a subclass of super, under the module’s namespace.</p>
</dd><dt>VALUE rb_define_module(const char *name) 
<dd>
<p>Defines a new Ruby module.</p>
</dd><dt>VALUE rb_define_module_under(VALUE module, const char *name) 
<dd>
<p>Defines a new Ruby module under the module’s namespace.</p>
</dd><dt>void rb_include_module(VALUE klass, VALUE module) 
<dd>
<p>Includes module into class.  If class already includes it, just ignored.</p>
</dd><dt>void rb_extend_object(VALUE object, VALUE module) 
<dd>
<p>Extend the object with the module’s attributes.</p>
</dd></dl>

<h3 id="label-Defining+global+variables">Defining global variables<span><a href="#label-Defining+global+variables">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>void rb_define_variable(const char *name, VALUE *var) 
<dd>
<p>Defines a global variable which is shared between C and Ruby.  If name contains a character which is not allowed to be part of the symbol, it can’t be seen from Ruby programs.</p>
</dd><dt>void rb_define_readonly_variable(const char *name, VALUE *var) 
<dd>
<p>Defines a read-only global variable.  Works just like rb_define_variable(), except the defined variable is read-only.</p>
</dd><dt>void rb_define_virtual_variable(const char *name, VALUE (*getter)(), void (*setter)()) 
<dd>
<p>Defines a virtual variable, whose behavior is defined by a pair of C functions.  The getter function is called when the variable is referenced.  The setter function is called when the variable is set to a value.  The prototype for getter/setter functions are:</p>

<pre>VALUE getter(ID id)
void setter(VALUE val, ID id)</pre>

<p>The getter function must return the value for the access.</p>
</dd><dt>void rb_define_hooked_variable(const char *name, VALUE *var, VALUE (*getter)(), void (*setter)()) 
<dd>
<p>Defines hooked variable.  It’s a virtual variable with a C variable. The getter is called as</p>

<pre>VALUE getter(ID id, VALUE *var)</pre>

<p>returning a new value.  The setter is called as</p>

<pre>void setter(VALUE val, ID id, VALUE *var)</pre>
</dd><dt>void rb_global_variable(VALUE *var) 
<dd>
<p>Tells <a href="GC.html"><code>GC</code></a> to protect C global variable, which holds Ruby value to be marked.</p>
</dd><dt>void rb_gc_register_mark_object(VALUE object) 
<dd>
<p>Tells <a href="GC.html"><code>GC</code></a> to protect the <code>object</code>, which may not be referenced anywhere.</p>
</dd></dl>

<h3 id="label-Constant+definition">Constant definition<span><a href="#label-Constant+definition">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>void rb_define_const(VALUE klass, const char *name, VALUE val) 
<dd>
<p>Defines a new constant under the class/module.</p>
</dd><dt>void rb_define_global_const(const char *name, VALUE val) 
<dd>
<p>Defines a global constant.  This is just the same as</p>

<pre class="ruby"><span class="ruby-identifier">rb_define_const</span>(<span class="ruby-identifier">rb_cObject</span>, <span class="ruby-identifier">name</span>, <span class="ruby-identifier">val</span>)
</pre>
</dd></dl>

<h3 id="label-Method+definition"><a href="Method.html"><code>Method</code></a> definition<span><a href="#label-Method+definition">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>rb_define_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) 
<dd>
<p>Defines a method for the class.  func is the function pointer.  argc is the number of arguments.  if argc is -1, the function will receive 3 arguments: argc, argv, and self.  if argc is -2, the function will receive 2 arguments, self and args, where args is a Ruby array of the method arguments.</p>
</dd><dt>rb_define_private_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) 
<dd>
<p>Defines a private method for the class.  Arguments are same as rb_define_method().</p>
</dd><dt>rb_define_singleton_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) 
<dd>
<p>Defines a singleton method.  Arguments are same as rb_define_method().</p>
</dd><dt>rb_check_arity(int argc, int min, int max) 
<dd>
<p>Check the number of arguments, argc is in the range of min..max.  If max is UNLIMITED_ARGUMENTS, upper bound is not checked.  If argc is out of bounds, an <a href="ArgumentError.html"><code>ArgumentError</code></a> will be raised.</p>
</dd><dt>rb_scan_args(int argc, VALUE *argv, const char *fmt, …) 
<dd>
<p>Retrieve argument from argc and argv to given VALUE references according to the format string.  The format can be described in ABNF as follows:</p>

<pre>scan-arg-spec  := param-arg-spec [keyword-arg-spec] [block-arg-spec]

param-arg-spec := pre-arg-spec [post-arg-spec] / post-arg-spec /
                  pre-opt-post-arg-spec
pre-arg-spec   := num-of-leading-mandatory-args [num-of-optional-args]
post-arg-spec  := sym-for-variable-length-args
                  [num-of-trailing-mandatory-args]
pre-opt-post-arg-spec := num-of-leading-mandatory-args num-of-optional-args
                         num-of-trailing-mandatory-args
keyword-arg-spec := sym-for-keyword-arg
block-arg-spec := sym-for-block-arg

num-of-leading-mandatory-args  := DIGIT ; The number of leading
                                        ; mandatory arguments
num-of-optional-args           := DIGIT ; The number of optional
                                        ; arguments
sym-for-variable-length-args   := &quot;*&quot;   ; Indicates that variable
                                        ; length arguments are
                                        ; captured as a ruby array
num-of-trailing-mandatory-args := DIGIT ; The number of trailing
                                        ; mandatory arguments
sym-for-keyword-arg            := &quot;:&quot;   ; Indicates that keyword
                                        ; argument captured as a hash.
                                        ; If keyword arguments are not
                                        ; provided, returns nil.
sym-for-block-arg              := &quot;&amp;&quot;   ; Indicates that an iterator
                                        ; block should be captured if
                                        ; given</pre>

<p>For example, “12” means that the method requires at least one argument, and at most receives three (1+2) arguments.  So, the format string must be followed by three variable references, which are to be assigned to captured arguments.  For omitted arguments, variables are set to Qnil.  NULL can be put in place of a variable reference, which means the corresponding captured argument(s) should be just dropped.</p>

<p>The number of given arguments, excluding an option hash or iterator block, is returned.</p>
</dd><dt>rb_scan_args_kw(int kw_splat, int argc, VALUE *argv, const char *fmt, …) 
<dd>
<p>The same as <code>rb_scan_args</code>, except the <code>kw_splat</code> argument specifies whether keyword arguments are provided (instead of being determined by the call from Ruby to the C function). <code>kw_splat</code> should be one of the following values:</p>
<dl class="rdoc-list note-list"><dt>RB_SCAN_ARGS_PASS_CALLED_KEYWORDS 
<dd>
<p>Same behavior as <code>rb_scan_args</code>.</p>
</dd><dt>RB_SCAN_ARGS_KEYWORDS 
<dd>
<p>The final argument should be a hash treated as keywords.</p>
</dd><dt>RB_SCAN_ARGS_LAST_HASH_KEYWORDS 
<dd>
<p>Treat a final argument as keywords if it is a hash, and not as keywords otherwise.</p>
</dd></dl>
</dd><dt>int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values) 
<dd>
<p>Retrieves argument VALUEs bound to keywords, which directed by <code>table</code> into <code>values</code>, deleting retrieved entries from <code>keyword_hash</code> along the way.  First <code>required</code> number of IDs referred by <code>table</code> are mandatory, and succeeding <code>optional</code> (- <code>optional</code> - 1 if <code>optional</code> is negative) number of IDs are optional.  If a mandatory key is not contained in <code>keyword_hash</code>, raises “missing keyword” <code>ArgumentError</code>.  If an optional key is not present in <code>keyword_hash</code>, the corresponding element in <code>values</code> is set to <code>Qundef</code>. If <code>optional</code> is negative, rest of <code>keyword_hash</code> are ignored, otherwise raises “unknown keyword” <code>ArgumentError</code>.</p>

<p>Be warned, handling keyword arguments in the C API is less efficient than handling them in Ruby.  Consider using a Ruby wrapper method around a non-keyword C function. ref: <a href="https://bugs.ruby-lang.org/issues/11339">bugs.ruby-lang.org/issues/11339</a></p>
</dd><dt>VALUE rb_extract_keywords(VALUE *original_hash) 
<dd>
<p>Extracts pairs whose key is a symbol into a new hash from a hash object referred by <code>original_hash</code>.  If the original hash contains non-symbol keys, then they are copied to another hash and the new hash is stored through <code>original_hash</code>, else 0 is stored.</p>
</dd></dl>

<h3 id="label-Invoking+Ruby+method">Invoking Ruby method<span><a href="#label-Invoking+Ruby+method">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>VALUE rb_funcall(VALUE recv, ID mid, int narg, …) 
<dd>
<p>Invokes a method.  To retrieve mid from a method name, use rb_intern(). Able to call even private/protected methods.</p>
</dd><dt>VALUE rb_funcall2(VALUE recv, ID mid, int argc, VALUE *argv) 
<dt>VALUE rb_funcallv(VALUE recv, ID mid, int argc, VALUE *argv) 
<dd>
<p>Invokes a method, passing arguments as an array of values. Able to call even private/protected methods.</p>
</dd><dt>VALUE rb_funcallv_kw(VALUE recv, ID mid, int argc, VALUE *argv, int kw_splat) 
<dd>
<p>Same as rb_funcallv, using <code>kw_splat</code> to determine whether keyword arguments are passed.</p>
</dd><dt>VALUE rb_funcallv_public(VALUE recv, ID mid, int argc, VALUE *argv) 
<dd>
<p>Invokes a method, passing arguments as an array of values. Able to call only public methods.</p>
</dd><dt>VALUE rb_funcallv_public_kw(VALUE recv, ID mid, int argc, VALUE *argv, int kw_splat) 
<dd>
<p>Same as rb_funcallv_public, using <code>kw_splat</code> to determine whether keyword arguments are passed.</p>
</dd><dt>VALUE rb_funcall_passing_block(VALUE recv, ID mid, int argc, const VALUE* argv) 
<dd>
<p>Same as rb_funcallv_public, except is passes the currently active block as the block when calling the method.</p>
</dd><dt>VALUE rb_funcall_passing_block_kw(VALUE recv, ID mid, int argc, const VALUE* argv, int kw_splat) 
<dd>
<p>Same as rb_funcall_passing_block, using <code>kw_splat</code> to determine whether keyword arguments are passed.</p>
</dd><dt>VALUE rb_funcall_with_block(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE passed_procval) 
<dd>
<p>Same as rb_funcallv_public, except <code>passed_procval</code> specifies the block to pass to the method.</p>
</dd><dt>VALUE rb_funcall_with_block_kw(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE passed_procval, int kw_splat) 
<dd>
<p>Same as rb_funcall_with_block, using <code>kw_splat</code> to determine whether keyword arguments are passed.</p>
</dd><dt>VALUE rb_eval_string(const char *str) 
<dd>
<p>Compiles and executes the string as a Ruby program.</p>
</dd><dt>ID rb_intern(const char *name) 
<dd>
<p>Returns ID corresponding to the name.</p>
</dd><dt>char *rb_id2name(ID id) 
<dd>
<p>Returns the name corresponding ID.</p>
</dd><dt>char *rb_class2name(VALUE klass) 
<dd>
<p>Returns the name of the class.</p>
</dd><dt>int rb_respond_to(VALUE obj, ID id) 
<dd>
<p>Returns true if the object responds to the message specified by id.</p>
</dd></dl>

<h3 id="label-Instance+variables">Instance variables<span><a href="#label-Instance+variables">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>VALUE rb_iv_get(VALUE obj, const char *name) 
<dd>
<p>Retrieve the value of the instance variable.  If the name is not prefixed by ‘@’, that variable shall be inaccessible from Ruby.</p>
</dd><dt>VALUE rb_iv_set(VALUE obj, const char *name, VALUE val) 
<dd>
<p>Sets the value of the instance variable.</p>
</dd></dl>

<h3 id="label-Control+structure">Control structure<span><a href="#label-Control+structure">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>VALUE rb_block_call(VALUE recv, ID mid, int argc, VALUE * argv, VALUE (*func) (ANYARGS), VALUE data2) 
<dd>
<p>Calls a method on the recv, with the method name specified by the symbol mid, with argc arguments in argv, supplying func as the block. When func is called as the block, it will receive the value from yield as the first argument, and data2 as the second argument. When yielded with multiple values (in C, rb_yield_values(), rb_yield_values2() and rb_yield_splat()), data2 is packed as an <a href="Array.html"><code>Array</code></a>, whereas yielded values can be gotten via argc/argv of the third/fourth arguments.</p>
</dd><dt>VALUE rb_block_call_kw(VALUE recv, ID mid, int argc, VALUE * argv, VALUE (*func) (ANYARGS), VALUE data2, int kw_splat) 
<dd>
<p>Same as rb_funcall_with_block, using <code>kw_splat</code> to determine whether keyword arguments are passed.</p>
</dd><dt>[OBSOLETE] VALUE rb_iterate(VALUE (*func1)(), VALUE arg1, VALUE (*func2)(), VALUE arg2) 
<dd>
<p>Calls the function func1, supplying func2 as the block.  func1 will be called with the argument arg1.  func2 receives the value from yield as the first argument, arg2 as the second argument.</p>

<p>When rb_iterate is used in 1.9, func1 has to call some Ruby-level method. This function is obsolete since 1.9; use rb_block_call instead.</p>
</dd><dt>VALUE rb_yield(VALUE val) 
<dd>
<p>Yields val as a single argument to the block.</p>
</dd><dt>VALUE rb_yield_values(int n, …) 
<dd>
<p>Yields <code>n</code> number of arguments to the block, using one C argument per Ruby argument.</p>
</dd><dt>VALUE rb_yield_values2(int n, VALUE *argv) 
<dd>
<p>Yields <code>n</code> number of arguments to the block, with all Ruby arguments in the C argv array.</p>
</dd><dt>VALUE rb_yield_values_kw(int n, VALUE *argv, int kw_splat) 
<dd>
<p>Same as rb_yield_values2, using <code>kw_splat</code> to determine whether keyword arguments are passed.</p>
</dd><dt>VALUE rb_yield_splat(VALUE args) 
<dd>
<p>Same as rb_yield_values2, except arguments are specified by the Ruby array <code>args</code>.</p>
</dd><dt>VALUE rb_yield_splat_kw(VALUE args, int kw_splat) 
<dd>
<p>Same as rb_yield_splat, using <code>kw_splat</code> to determine whether keyword arguments are passed.</p>
</dd><dt>VALUE rb_rescue(VALUE (*func1)(ANYARGS), VALUE arg1, VALUE (*func2)(ANYARGS), VALUE arg2) 
<dd>
<p>Calls the function func1, with arg1 as the argument.  If an exception occurs during func1, it calls func2 with arg2 as the first argument and the exception object as the second argument.  The return value of rb_rescue() is the return value from func1 if no exception occurs, from func2 otherwise.</p>
</dd><dt>VALUE rb_ensure(VALUE (*func1)(ANYARGS), VALUE arg1, VALUE (*func2)(ANYARGS), VALUE arg2) 
<dd>
<p>Calls the function func1 with arg1 as the argument, then calls func2 with arg2 if execution terminated.  The return value from rb_ensure() is that of func1 when no exception occurred.</p>
</dd><dt>VALUE rb_protect(VALUE (*func) (VALUE), VALUE arg, int *state) 
<dd>
<p>Calls the function func with arg as the argument.  If no exception occurred during func, it returns the result of func and *state is zero. Otherwise, it returns Qnil and sets *state to nonzero.  If state is NULL, it is not set in both cases. You have to clear the error info with rb_set_errinfo(Qnil) when ignoring the caught exception.</p>
</dd><dt>void rb_jump_tag(int state) 
<dd>
<p>Continues the exception caught by rb_protect() and rb_eval_string_protect(). state must be the returned value from those functions.  This function never return to the caller.</p>
</dd><dt>void rb_iter_break() 
<dd>
<p>Exits from the current innermost block.  This function never return to the caller.</p>
</dd><dt>void rb_iter_break_value(VALUE value) 
<dd>
<p>Exits from the current innermost block with the value.  The block will return the given argument value.  This function never return to the caller.</p>
</dd></dl>

<h3 id="label-Exceptions+and+errors">Exceptions and errors<span><a href="#label-Exceptions+and+errors">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>void rb_warn(const char *fmt, …) 
<dd>
<p>Prints a warning message according to a printf-like format.</p>
</dd><dt>void rb_warning(const char *fmt, …) 
<dd>
<p>Prints a warning message according to a printf-like format, if $VERBOSE is true.</p>
</dd><dt>void rb_raise(rb_eRuntimeError, const char *fmt, …) 
<dd>
<p>Raises <a href="RuntimeError.html"><code>RuntimeError</code></a>.  The fmt is a format string just like printf().</p>
</dd><dt>void rb_raise(VALUE exception, const char *fmt, …) 
<dd>
<p>Raises a class exception.  The fmt is a format string just like printf().</p>
</dd><dt>void rb_fatal(const char *fmt, …) 
<dd>
<p>Raises a fatal error, terminates the interpreter.  No exception handling will be done for fatal errors, but ensure blocks will be executed.</p>
</dd><dt>void rb_bug(const char *fmt, …) 
<dd>
<p>Terminates the interpreter immediately.  This function should be called under the situation caused by the bug in the interpreter.  No exception handling nor ensure execution will be done.</p>
</dd></dl>

<p>Note: In the format string, “%”PRIsVALUE can be used for <a href="Object.html#method-i-to_s"><code>Object#to_s</code></a> (or <a href="Object.html#method-i-inspect"><code>Object#inspect</code></a> if ‘+’ flag is set) output (and related argument must be a VALUE).  Since it conflicts with “%i”, for integers in format strings, use “%d”.</p>

<h3 id="label-Threading">Threading<span><a href="#label-Threading">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>As of Ruby 1.9, Ruby supports native 1:1 threading with one kernel thread per Ruby <a href="Thread.html"><code>Thread</code></a> object.  Currently, there is a GVL (Global VM Lock) which prevents simultaneous execution of Ruby code which may be released by the rb_thread_call_without_gvl and rb_thread_call_without_gvl2 functions. These functions are tricky-to-use and documented in thread.c; do not use them before reading comments in thread.c.</p>
<dl class="rdoc-list note-list"><dt>void rb_thread_schedule(void) 
<dd>
<p>Give the scheduler a hint to pass execution to another thread.</p>
</dd></dl>

<h3 id="label-Input-2FOutput+-28IO-29+on+a+single+file+descriptor">Input/Output (<a href="IO.html"><code>IO</code></a>) on a single file descriptor<span><a href="#label-Input-2FOutput+-28IO-29+on+a+single+file+descriptor">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>int rb_io_wait_readable(int fd) 
<dd>
<p>Wait indefinitely for the given FD to become readable, allowing other threads to be scheduled.  Returns a true value if a read may be performed, false if there is an unrecoverable error.</p>
</dd><dt>int rb_io_wait_writable(int fd) 
<dd>
<p>Like rb_io_wait_readable, but for writability.</p>
</dd><dt>int rb_wait_for_single_fd(int fd, int events, struct timeval *timeout) 
<dd>
<p>Allows waiting on a single FD for one or multiple events with a specified timeout.</p>

<p><code>events</code> is a mask of any combination of the following values:</p>
<ul><li>
<p>RB_WAITFD_IN - wait for readability of normal data</p>
</li><li>
<p>RB_WAITFD_OUT - wait for writability</p>
</li><li>
<p>RB_WAITFD_PRI - wait for readability of urgent data</p>
</li></ul>

<p>Use a NULL <code>timeout</code> to wait indefinitely.</p>
</dd></dl>

<h3 id="label-I-2FO+multiplexing">I/O multiplexing<span><a href="#label-I-2FO+multiplexing">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>Ruby supports I/O multiplexing based on the select(2) system call. The Linux select_tut(2) manpage &lt;<a href="http://man7.org/linux/man-pages/man2/select_tut.2.html">man7.org/linux/man-pages/man2/select_tut.2.html</a>&gt; provides a good overview on how to use select(2), and the Ruby API has analogous functions and data structures to the well-known select API. Understanding of select(2) is required to understand this section.</p>
<dl class="rdoc-list note-list"><dt>typedef struct rb_fdset_t 
<dd>
<p>The data structure which wraps the fd_set bitmap used by select(2). This allows Ruby to use FD sets larger than that allowed by historic limitations on modern platforms.</p>
</dd><dt>void rb_fd_init(rb_fdset_t *) 
<dd>
<p>Initializes the rb_fdset_t, it must be initialized before other rb_fd_* operations.  Analogous to calling malloc(3) to allocate an fd_set.</p>
</dd><dt>void rb_fd_term(rb_fdset_t *) 
<dd>
<p>Destroys the rb_fdset_t, releasing any memory and resources it used. It must be reinitialized using rb_fd_init before future use. Analogous to calling free(3) to release memory for an fd_set.</p>
</dd><dt>void rb_fd_zero(rb_fdset_t *) 
<dd>
<p>Clears all FDs from the rb_fdset_t, analogous to FD_ZERO(3).</p>
</dd><dt>void rb_fd_set(int fd, rb_fdset_t *) 
<dd>
<p>Adds a given FD in the rb_fdset_t, analogous to FD_SET(3).</p>
</dd><dt>void rb_fd_clr(int fd, rb_fdset_t *) 
<dd>
<p>Removes a given FD from the rb_fdset_t, analogous to FD_CLR(3).</p>
</dd><dt>int rb_fd_isset(int fd, const rb_fdset_t *) 
<dd>
<p>Returns true if a given FD is set in the rb_fdset_t, false if not. Analogous to FD_ISSET(3).</p>
</dd><dt>int rb_thread_fd_select(int nfds, rb_fdset_t *readfds, rb_fdset_t *writefds, rb_fdset_t *exceptfds, struct timeval *timeout) 
<dd>
<p>Analogous to the select(2) system call, but allows other Ruby threads to be scheduled while waiting.</p>

<p>When only waiting on a single FD, favor rb_io_wait_readable, rb_io_wait_writable, or rb_wait_for_single_fd functions since they can be optimized for specific platforms (currently, only Linux).</p>
</dd></dl>

<h3 id="label-Initialize+and+start+the+interpreter">Initialize and start the interpreter<span><a href="#label-Initialize+and+start+the+interpreter">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>The embedding API functions are below (not needed for extension libraries):</p>
<dl class="rdoc-list note-list"><dt>void ruby_init() 
<dd>
<p>Initializes the interpreter.</p>
</dd><dt>void *ruby_options(int argc, char **argv) 
<dd>
<p><a href="Process.html"><code>Process</code></a> command line arguments for the interpreter. And compiles the Ruby source to execute. It returns an opaque pointer to the compiled source or an internal special value.</p>
</dd><dt>int ruby_run_node(void *n) 
<dd>
<p>Runs the given compiled source and exits this process. It returns EXIT_SUCCESS if successfully runs the source. Otherwise, it returns other value.</p>
</dd><dt>void ruby_script(char *name) 
<dd>
<p>Specifies the name of the script ($0).</p>
</dd></dl>

<h3 id="label-Hooks+for+the+interpreter+events">Hooks for the interpreter events<span><a href="#label-Hooks+for+the+interpreter+events">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>void rb_add_event_hook(rb_event_hook_func_t func, rb_event_flag_t events, VALUE data) 
<dd>
<p>Adds a hook function for the specified interpreter events. events should be OR’ed value of:</p>

<pre class="ruby"><span class="ruby-constant">RUBY_EVENT_LINE</span>
<span class="ruby-constant">RUBY_EVENT_CLASS</span>
<span class="ruby-constant">RUBY_EVENT_END</span>
<span class="ruby-constant">RUBY_EVENT_CALL</span>
<span class="ruby-constant">RUBY_EVENT_RETURN</span>
<span class="ruby-constant">RUBY_EVENT_C_CALL</span>
<span class="ruby-constant">RUBY_EVENT_C_RETURN</span>
<span class="ruby-constant">RUBY_EVENT_RAISE</span>
<span class="ruby-constant">RUBY_EVENT_ALL</span>
</pre>

<p>The definition of rb_event_hook_func_t is below:</p>

<pre>typedef void (*rb_event_hook_func_t)(rb_event_t event, VALUE data,
                                     VALUE self, ID id, VALUE klass)</pre>

<p>The third argument ‘data’ to rb_add_event_hook() is passed to the hook function as the second argument, which was the pointer to the current NODE in 1.8.  See RB_EVENT_HOOKS_HAVE_CALLBACK_DATA below.</p>
</dd><dt>int rb_remove_event_hook(rb_event_hook_func_t func) 
<dd>
<p>Removes the specified hook function.</p>
</dd></dl>

<h3 id="label-Memory+usage">Memory usage<span><a href="#label-Memory+usage">&para;</a> <a href="#top">&uarr;</a></span></h3>
<dl class="rdoc-list note-list"><dt>void rb_gc_adjust_memory_usage(ssize_t diff) 
<dd>
<p>Adjusts the amount of registered external memory.  You can tell <a href="GC.html"><code>GC</code></a> how much memory is used by an external library by this function.  Calling this function with positive diff means the memory usage is increased; new memory block is allocated or a block is reallocated as larger size.  Calling this function with negative diff means the memory usage is decreased; a memory block is freed or a block is reallocated as smaller size.  This function may trigger the <a href="GC.html"><code>GC</code></a>.</p>
</dd></dl>

<h3 id="label-Macros+for+compatibility">Macros for compatibility<span><a href="#label-Macros+for+compatibility">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>Some macros to check API compatibilities are available by default.</p>
<dl class="rdoc-list note-list"><dt>NORETURN_STYLE_NEW 
<dd>
<p>Means that NORETURN macro is functional style instead of prefix.</p>
</dd><dt>HAVE_RB_DEFINE_ALLOC_FUNC 
<dd>
<p>Means that function rb_define_alloc_func() is provided, that means the allocation framework is used.  This is the same as the result of have_func(“rb_define_alloc_func”, “ruby.h”).</p>
</dd><dt>HAVE_RB_REG_NEW_STR 
<dd>
<p>Means that function rb_reg_new_str() is provided, that creates <a href="Regexp.html"><code>Regexp</code></a> object from <a href="String.html"><code>String</code></a> object.  This is the same as the result of have_func(“rb_reg_new_str”, “ruby.h”).</p>
</dd><dt>HAVE_RB_IO_T 
<dd>
<p>Means that type rb_io_t is provided.</p>
</dd><dt>USE_SYMBOL_AS_METHOD_NAME 
<dd>
<p>Means that Symbols will be returned as method names, e.g., <a href="Object.html#method-i-methods"><code>Module#methods</code></a>, #singleton_methods and so on.</p>
</dd><dt>HAVE_RUBY_*_H 
<dd>
<p>Defined in ruby.h and means corresponding header is available.  For instance, when HAVE_RUBY_ST_H is defined you should use ruby/st.h not mere st.h.</p>

<p>Header files corresponding to these macros may be <code>#include</code> directly from extension libraries.</p>
</dd><dt>RB_EVENT_HOOKS_HAVE_CALLBACK_DATA 
<dd>
<p>Means that rb_add_event_hook() takes the third argument ‘data’, to be passed to the given event hook function.</p>
</dd></dl>

<h3 id="label-Defining+backward+compatible+macros+for+keyword+argument+functions">Defining backward compatible macros for keyword argument functions<span><a href="#label-Defining+backward+compatible+macros+for+keyword+argument+functions">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>Most ruby C extensions are designed to support multiple Ruby versions. In order to correctly support Ruby 2.7+ in regards to keyword argument separation, C extensions need to use <code>*_kw</code> functions.  However, these functions do not exist in Ruby 2.6 and below, so in those cases macros should be defined to allow you to use the same code on multiple Ruby versions.  Here are example macros you can use in extensions that support Ruby 2.6 (or below) when using the <code>*_kw</code> functions introduced in Ruby 2.7.</p>

<pre>#ifndef RB_PASS_KEYWORDS
/* Only define macros on Ruby &lt;2.7 */
#define rb_funcallv_kw(o, m, c, v, kw) rb_funcallv(o, m, c, v)
#define rb_funcallv_public_kw(o, m, c, v, kw) rb_funcallv_public(o, m, c, v)
#define rb_funcall_passing_block_kw(o, m, c, v, kw) rb_funcall_passing_block(o, m, c, v)
#define rb_funcall_with_block_kw(o, m, c, v, b, kw) rb_funcall_with_block(o, m, c, v, b)
#define rb_scan_args_kw(kw, c, v, s, ...) rb_scan_args(c, v, s, __VA_ARGS__)
#define rb_call_super_kw(c, v, kw) rb_call_super(c, v)
#define rb_yield_values_kw(c, v, kw) rb_yield_values2(c, v)
#define rb_yield_splat_kw(a, kw) rb_yield_splat(a)
#define rb_block_call_kw(o, m, c, v, f, p, kw) rb_block_call(o, m, c, v, f, p)
#define rb_fiber_resume_kw(o, c, v, kw) rb_fiber_resume(o, c, v)
#define rb_fiber_yield_kw(c, v, kw) rb_fiber_yield(c, v)
#define rb_enumeratorize_with_size_kw(o, m, c, v, f, kw) rb_enumeratorize_with_size(o, m, c, v, f)
#define SIZED_ENUMERATOR_KW(obj, argc, argv, size_fn, kw_splat) \
    rb_enumeratorize_with_size((obj), ID2SYM(rb_frame_this_func()), \
                               (argc), (argv), (size_fn))
#define RETURN_SIZED_ENUMERATOR_KW(obj, argc, argv, size_fn, kw_splat) do { \
        if (!rb_block_given_p())                                            \
            return SIZED_ENUMERATOR(obj, argc, argv, size_fn);              \
    } while (0)
#define RETURN_ENUMERATOR_KW(obj, argc, argv, kw_splat) RETURN_SIZED_ENUMERATOR(obj, argc, argv, 0)
#define rb_check_funcall_kw(o, m, c, v, kw) rb_check_funcall(o, m, c, v)
#define rb_obj_call_init_kw(o, c, v, kw) rb_obj_call_init(o, c, v)
#define rb_class_new_instance_kw(c, v, k, kw) rb_class_new_instance(c, v, k)
#define rb_proc_call_kw(p, a, kw) rb_proc_call(p, a)
#define rb_proc_call_with_block_kw(p, c, v, b, kw) rb_proc_call_with_block(p, c, v, b)
#define rb_method_call_kw(c, v, m, kw) rb_method_call(c, v, m)
#define rb_method_call_with_block_kw(c, v, m, b, kw) rb_method_call_with_block(c, v, m, b)
#define rb_eval_cmd_kwd(c, a, kw) rb_eval_cmd(c, a, 0)
#endif</pre>

<h2 id="label-Appendix+C.+Functions+available+for+use+in+extconf.rb">Appendix C. Functions available for use in extconf.rb<span><a href="#label-Appendix+C.+Functions+available+for+use+in+extconf.rb">&para;</a> <a href="#top">&uarr;</a></span></h2>

<p>See documentation for MakeMakefile.</p>

<h2 id="label-Appendix+D.+Generational+GC">Appendix D. Generational <a href="GC.html"><code>GC</code></a><span><a href="#label-Appendix+D.+Generational+GC">&para;</a> <a href="#top">&uarr;</a></span></h2>

<p>Ruby 2.1 introduced a generational garbage collector (called RGenGC). RGenGC (mostly) keeps compatibility.</p>

<p>Generally, the use of the technique called write barriers is required in extension libraries for generational <a href="GC.html"><code>GC</code></a> (<a href="https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29">en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29</a>). RGenGC works fine without write barriers in extension libraries.</p>

<p>If your library adheres to the following tips, performance can be further improved. Especially, the “Don’t touch pointers directly” section is important.</p>

<h3 id="label-Incompatibility">Incompatibility<span><a href="#label-Incompatibility">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>You can’t write RBASIC(obj)-&gt;klass field directly because it is const value now.</p>

<p>Basically you should not write this field because MRI expects it to be an immutable field, but if you want to do it in your extension you can use the following functions:</p>
<dl class="rdoc-list note-list"><dt>VALUE rb_obj_hide(VALUE obj) 
<dd>
<p>Clear RBasic::klass field. The object will be an internal object. <a href="ObjectSpace.html#method-c-each_object"><code>ObjectSpace::each_object</code></a> can’t find this object.</p>
</dd><dt>VALUE rb_obj_reveal(VALUE obj, VALUE klass) 
<dd>
<p>Reset RBasic::klass to be klass. We expect the ‘klass’ is hidden class by rb_obj_hide().</p>
</dd></dl>

<h3 id="label-Write+barriers">Write barriers<span><a href="#label-Write+barriers">&para;</a> <a href="#top">&uarr;</a></span></h3>

<p>RGenGC doesn’t require write barriers to support generational <a href="GC.html"><code>GC</code></a>. However, caring about write barrier can improve the performance of RGenGC. Please check the following tips.</p>

<h4 id="label-Don-27t+touch+pointers+directly">Don’t touch pointers directly<span><a href="#label-Don-27t+touch+pointers+directly">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>In MRI (include/ruby/ruby.h), some macros to acquire pointers to the internal data structures are supported such as RARRAY_PTR(), RSTRUCT_PTR() and so on.</p>

<p>DO NOT USE THESE MACROS and instead use the corresponding C-APIs such as rb_ary_aref(), rb_ary_store() and so on.</p>

<h4 id="label-Consider+whether+to+insert+write+barriers">Consider whether to insert write barriers<span><a href="#label-Consider+whether+to+insert+write+barriers">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>You don’t need to care about write barriers if you only use built-in types.</p>

<p>If you support T_DATA objects, you may consider using write barriers.</p>

<p>Inserting write barriers into T_DATA objects only works with the following type objects: (a) long-lived objects, (b) when a huge number of objects are generated and (c) container-type objects that have references to other objects. If your extension provides such a type of T_DATA objects, consider inserting write barriers.</p>

<p>(a): short-lived objects don’t become old generation objects. (b): only a few oldgen objects don’t have performance impact. (c): only a few references don’t have performance impact.</p>

<p>Inserting write barriers is a very difficult hack, it is easy to introduce critical bugs. And inserting write barriers has several areas of overhead. Basically we don’t recommend you insert write barriers. Please carefully consider the risks.</p>

<h4 id="label-Combine+with+built-in+types">Combine with built-in types<span><a href="#label-Combine+with+built-in+types">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>Please consider utilizing built-in types. Most built-in types support write barrier, so you can use them to avoid manually inserting write barriers.</p>

<p>For example, if your T_DATA has references to other objects, then you can move these references to <a href="Array.html"><code>Array</code></a>. A T_DATA object only has a reference to an array object. Or you can also use a <a href="Struct.html"><code>Struct</code></a> object to gather a T_DATA object (without any references) and an that <a href="Array.html"><code>Array</code></a> contains references.</p>

<p>With use of such techniques, you don’t need to insert write barriers anymore.</p>

<h4 id="label-Insert+write+barriers">Insert write barriers<span><a href="#label-Insert+write+barriers">&para;</a> <a href="#top">&uarr;</a></span></h4>

<p>[AGAIN] Inserting write barriers is a very difficult hack, and it is easy to introduce critical bugs. And inserting write barriers has several areas of overhead. Basically we don’t recommend you insert write barriers. Please carefully consider the risks.</p>

<p>Before inserting write barriers, you need to know about RGenGC algorithm (gc.c will help you). Macros and functions to insert write barriers are available in include/ruby/ruby.h. An example is available in iseq.c.</p>

<p>For a complete guide for RGenGC and write barriers, please refer to &lt;<a href="https://bugs.ruby-lang.org/projects/ruby-master/wiki/RGenGC">bugs.ruby-lang.org/projects/ruby-master/wiki/RGenGC</a>&gt;.</p>

<h2 id="label-Appendix+E.+RB_GC_GUARD+to+protect+from+premature+GC">Appendix E. RB_GC_GUARD to protect from premature <a href="GC.html"><code>GC</code></a><span><a href="#label-Appendix+E.+RB_GC_GUARD+to+protect+from+premature+GC">&para;</a> <a href="#top">&uarr;</a></span></h2>

<p>C Ruby currently uses conservative garbage collection, thus VALUE variables must remain visible on the stack or registers to ensure any associated data remains usable.  Optimizing C compilers are not designed with conservative garbage collection in mind, so they may optimize away the original VALUE even if the code depends on data associated with that VALUE.</p>

<p>The following example illustrates the use of RB_GC_GUARD to ensure the contents of sptr remain valid while the second invocation of rb_str_new_cstr is running.</p>

<pre>VALUE s, w;
const char *sptr;

s = rb_str_new_cstr(&quot;hello world!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!&quot;);
sptr = RSTRING_PTR(s);
w = rb_str_new_cstr(sptr + 6); /* Possible GC invocation */

RB_GC_GUARD(s); /* ensure s (and thus sptr) do not get GC-ed */</pre>

<p>In the above example, RB_GC_GUARD must be placed <em>after</em> the last use of sptr.  Placing RB_GC_GUARD before dereferencing sptr would be of no use. RB_GC_GUARD is only effective on the VALUE data type, not converted C data types.</p>

<p>RB_GC_GUARD would not be necessary at all in the above example if non-inlined function calls are made on the ‘s’ VALUE after sptr is dereferenced.  Thus, in the above example, calling any un-inlined function on ‘s’ such as:</p>

<pre class="ruby"><span class="ruby-identifier">rb_str_modify</span>(<span class="ruby-identifier">s</span>);
</pre>

<p>Will ensure ‘s’ stays on the stack or register to prevent a <a href="GC.html"><code>GC</code></a> invocation from prematurely freeing it.</p>

<p>Using the RB_GC_GUARD macro is preferable to using the “volatile” keyword in C.  RB_GC_GUARD has the following advantages:</p>
<ol><li>
<p>the intent of the macro use is clear</p>
</li><li>
<p>RB_GC_GUARD only affects its call site, “volatile” generates some extra code every time the variable is used, hurting optimization.</p>
</li><li>
<p>“volatile” implementations may be buggy/inconsistent in some compilers and architectures. RB_GC_GUARD is customizable for broken systems/compilers without negatively affecting other systems.</p>
</li></ol>

<h2 id="label-Appendix+F.+Ractor+support">Appendix F. <a href="Ractor.html"><code>Ractor</code></a> support<span><a href="#label-Appendix+F.+Ractor+support">&para;</a> <a href="#top">&uarr;</a></span></h2>

<p>Ractor(s) are the parallel execution mechanism introduced in Ruby 3.0. All ractors can run in parallel on a different OS thread (using an underlying system provided thread), so the C extension should be thread-safe. A C extension that can run in multiple ractors is called “Ractor-safe”.</p>

<p><a href="Ractor.html"><code>Ractor</code></a> safety around C extensions has the following properties:</p>
<ol><li>
<p>By default, all C extensions are recognized as Ractor-unsafe.</p>
</li><li>
<p>Ractor-unsafe C-methods may only be called from the main <a href="Ractor.html"><code>Ractor</code></a>.  If invoked by a non-main <a href="Ractor.html"><code>Ractor</code></a>, then a <a href="Ractor/UnsafeError.html"><code>Ractor::UnsafeError</code></a> is raised.</p>
</li><li>
<p>If an extension desires to be marked as Ractor-safe the extension should call rb_ext_ractor_safe(true) at the Init_ function for the extension, and all defined methods will be marked as Ractor-safe.</p>
</li></ol>

<p>To make a “Ractor-safe” C extension, we need to check the following points:</p>

<p>(1) Do not share unshareable objects between ractors</p>

<p>For example, C’s global variable can lead sharing an unshareable objects between ractors.</p>

<pre>VALUE g_var;
VALUE set(VALUE self, VALUE v){ return g_var = v; }
VALUE get(VALUE self){ return g_var; }</pre>

<p>set() and get() pair can share an unshareable objects using g_var, and it is Ractor-unsafe.</p>

<p>Not only using global variables directly, some indirect data structure such as global st_table can share the objects, so please take care.</p>

<p>Note that class and module objects are shareable objects, so you can keep the code “cFoo = rb_define_class(…)” with C’s global variables.</p>

<p>(2) Check the thread-safety of the extension</p>

<p>An extension should be thread-safe. For example, the following code is not thread-safe:</p>

<pre>bool g_called = false;
VALUE call(VALUE self) {
  if (g_called) rb_raise(&quot;recursive call is not allowed.&quot;);
  g_called = true;
  VALUE ret = do_something();
  g_called = false;
  return ret;
}</pre>

<p>because g_called global variable should be synchronized by other ractor’s threads. To avoid such data-race, some synchronization should be used. Check include/ruby/thread_native.h and include/ruby/atomic.h.</p>

<p>With Ractors, all objects given as method parameters and the receiver (self) are guaranteed to be from the current <a href="Ractor.html"><code>Ractor</code></a> or to be shareable. As a consequence, it is easier to make code ractor-safe than to make code generally thread-safe. For example, we don’t need to lock an array object to access the element of it.</p>

<p>(3) Check the thread-safety of any used library</p>

<p>If the extension relies on an external library, such as a function foo() from a library libfoo, the function libfoo foo() should be thread safe.</p>

<p>(4) Make an object shareable</p>

<p>This is not required to make an extension Ractor-safe.</p>

<p>If an extension provides special objects defined by rb_data_type_t, consider these objects can become shareable or not.</p>

<p>RUBY_TYPED_FROZEN_SHAREABLE flag indicates that these objects can be shareable objects if the object is frozen. This means that if the object is frozen, the mutation of wrapped data is not allowed.</p>

<p>(5) Others</p>

<p>There are possibly other points or requirements which must be considered in the making of a Ractor-safe extension.  This document will be extended as they are discovered.</p>

</main>

</div>  <!--  class='wrapper hdiv' -->


<footer id="validator-badges" role="contentinfo">
<p><a href="https://validator.w3.org/check/referer">Validate</a></p>
<p>Generated by <a href="https://ruby.github.io/rdoc/">RDoc</a> 6.4.0.</p>
<p>Based on <a href="https://github.com/ged/darkfish/">Darkfish</a> by <a href="http://deveiate.org">Michael Granger</a>.</p>

  
    <p><p><a href="https://ruby-doc.org">Ruby-doc.org</a> is a service of <a href="https://jamesbritt.com">James Britt</a> and <a href="https://neurogami.com">Neurogami</a>, purveyors of fine <a href='https://jamesbritt.bandcamp.com/'>dance noise</a></p>
</p>
  
  </footer>

<script type="text/javascript">


  let ads  = $("#carbonads-container").children().detach();


  function swapMode() {
    var cookieName = 'darkmode';
    var cssDarkmode = Cookies.get(cookieName);
    console.log("***** swapMode! " + cssDarkmode + " *****");


    if (cssDarkmode == "true") {
      console.log("We have dark mode, set the css to light ...");
      $('#rdoccss').attr("href", defaultModeCssHref);
      $('#cssSelect').text("Dark mode");
      cssDarkmode = "false";
      console.log("swapMode! Now set cookie to " + cssDarkmode);
      Cookies.set(cookieName, cssDarkmode);

    } else {
      console.log("We not have dark mode, set the css to dark ...");
      $('#rdoccss').attr("href", darkModeCsseHref);
      $('#cssSelect').text("Light mode");
      cssDarkmode = "true";
      console.log("swapMode! Now set cookie to " + cssDarkmode);
      Cookies.set(cookieName, cssDarkmode);

    }

    console.log("  --------------- ");
  }


const vueCssApp = new Vue({
el: '#menubar',
data: {
isDark: false
},
methods: {
toggleClass: function(event){
this.isDark = !this.isDark;
}
}
})

const vueApp = new Vue({
el: '#vapp',
data: { 
isOpen: true
},

mounted() {
this.handleResize();
this.manage_mob_classes();
window.addEventListener('resize', this.handleResize)
//this.isOpen !=  (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent));
},
destroyed() {
window.removeEventListener('resize', this.handleResize)
},
created() {
//manage_mob_classes();
},

methods : {
isMobile() {
  return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent));
},

  handleResize() {
    if (!this.isMobile()) {
      this.isOpen = window.innerWidth > 800;
    }
  },

  manage_mob_classes() {
    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
      $("nav").addClass("mob_nav");
      $("main").addClass("mob_main");
      $("#extraz").addClass("mob_extraz");
      $("#carbonads-container").addClass("mob_carbonads-container");
      this.isOpen  = false;
    } else {
      $("nav").removeClass("mob_nav") 
        $("main").removeClass("mob_main");
      $("#extraz").removeClass("mob_extraz");
      $("#carbonads-container").removeClass("mob_carbonads-container");
      this.isOpen  = true;
    }
  },

  toggleNav() {
    this.isOpen =! this.isOpen ;
    // alert("Toggle nav!");
    console.log("toggleNav() click: " + this.isOpen );
  }
}
})

$("#carbonads-container").append(ads);


$(function() {

    var darkmode = Cookies.get("darkmode");
    console.log("Document ready: " + darkmode);

    if ( darkmode  == "true" ) {
      $('#cssSelect').text("Light mode");
    } else {
      $('#cssSelect').text("Dark mode");
     }

    $('body').css('display','block');
    });

</script>

    
  </body> 
</html>

